jsp对同名checkbox的处理

来源:互联网 发布:齐博cms模板 编辑:程序博客网 时间:2024/05/21 07:15

jsp开发中经常会遇到同名的checkbox的问题,比如全选批量删除,用户多选提交等等。下面举个注册的例子。

代码如下:

 <body>  <div style="text-align:left">   <form action="request2.jsp" method="post" name="loginForm">    帐号:<input type="text" name="username" id="username" class="username"><span id="uMsg" style="font-size:14px;color:red"></span><br>    密码:<input type="password" name="password" id="pwd" class="pwd"><span id="pMsg" style="font-size:14px;color:red"></span><br>    爱好:<input type="checkbox" value="电影" name="ah">电影,<input type="checkbox" name="ah" value="看书">看书,<input type="checkbox" name="ah" value="上网">上网,<input type="checkbox" name="ah" value="游戏">游戏<br>    <input type="button"  class="btn" value="注册" onclick="return checkSubmit()"/>    <input type="reset" class="btn" value="重写">    </form>   </div>  </body>

从代码中我们可以看出,“爱好”使用的是checkbox而且名称都为“ah”,那么对于jsp来说在后台如何取到爱好的值呢?显然使用request.getParameter("ah")只能取到一个值,不能满足要求,那么有没有别的方法可以实现这一功能呢?答案是肯定的,jsp中提供了getParameterValues("")方法就可以获取同名表单的所有值。跟getParameter("")不同的是此方法返回类型是String[],里面存放的值就是我们选择的值。

JSP处理页面:request2.jsp

<body>    <%        //获取表单或者url传递过来的值    String username = request.getParameter("username");    out.println("用户名称:"+ username+"<br>");    //getParameterValues方法用来获取表单名称一样但有多个值:比如:checkbox    String[] ah = request.getParameterValues("ah");    out.println("爱好:");    for(String a:ah){    out.println(a+"  ");    }        %>     </body>


结果运行结果如下图:


原创粉丝点击