1

我正在使用以下代码来处理 html 按钮事件:

if(request.getParameter("btnSubmit")!=null)

我正在使用以下代码来捕获具有相同名称(“选择”)的选定复选框:

String[] selecttype = request.getParameterValues("choices");

if (selecttype != null && selecttype.length != 0) 
{
    for (int i = 0; i < selecttype.length; i++) 
    { 
    out.println("<h4><font color = 'red'>" + selecttype[i] + "</font></h4>");
      }
}

问题是,在按下按钮提交之前,选定复选框的值会显示在屏幕上。但是,当按下按钮提交时,这些值消失了。请问有什么帮助吗?!

4

1 回答 1

0

您需要某种逻辑来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>)更合适的数据结构来保存捕获的选择,但这应该让您了解必须做什么。

于 2013-05-01T23:45:38.010 回答