您需要某种逻辑来checked
根据捕获的选项设置复选框中的属性(即,勾选先前选择的复选框)。我建议您将表单提交给负责处理捕获的选择的中间 Servlet,将它们存储到比字符串数组更合适的数据结构中,并将请求转发回您的 jsp 页面,这也将使业务逻辑与看法。
无论如何,如果你真的需要在没有中间 Servlet 的情况下重新提交到同一个页面,这里有一种处理checked
属性的惰性方法:
<%
// Put this scriptet before your checkboxes
String[] choiceArray = request.getParameterValues("choices");
// avoids NPEs
Set<String> capturedChoices = new HashSet<String>();
if (choiceArray != null) {
capturedChoices = new HashSet<String>(Arrays.asList(choiceArray));
}
%>
在您的复选框渲染代码中:
<input type="checkbox" name="choices" value="choice1"
<%= capturedChoices.contains("choice1") ? "checked=\"checked\"" : "" %> />
<input type="checkbox" name="choices" value="choice2"
<%= capturedChoices.contains("choice2") ? "checked=\"checked\"" : "" %> />
<!-- And so on (replace `choice1`, `choice2`, etc with actual values). -->
当然,有比Set<String>
(例如,boolean[]
或Map<String, Boolean>
)更合适的数据结构来保存捕获的选择,但这应该让您了解必须做什么。