带复选框 checkbox 的列表要实现批量删除的功能,首先要获取被选中的信息的全部 id,可以把该列表放入一个 form 表单中,以获取表单信息的方式获取全部 id,然后遍历 id,循环删除所有信息。 列表形式:
获取列表选中信息 id 把 table 放入 form表单,并把复选框 checkbox 的 value 值设置为 id:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <form id ="form1" action ="${pageContext.request.contextPath}/delSelectedServlet" method ="post" > <table border ="1" class ="table table-bordered table-hover" > <tr class ="success" > <th > <input type ="checkbox" id ="firstCb" > </th > <th > 编号</th > <th > 姓名</th > <th > 性别</th > <th > 年龄</th > <th > 籍贯</th > <th > QQ</th > <th > 邮箱</th > <th > 操作</th > </tr > <c:forEach items ="${users}" var ="user" varStatus ="s" > <tr > <th > <input type ="checkbox" name ="uid" value ="${user.id}" > </th > <td > ${s.count}</td > <td > ${user.name}</td > <td > ${user.gender}</td > <td > ${user.age}</td > <td > ${user.address}</td > <td > ${user.qq}</td > <td > ${user.email}</td > <td > <a class ="btn btn-default btn-sm" href ="${pageContext.request.contextPath}/findUserServlet?id=${user.id}" > 修改</a > <a class ="btn btn-default btn-sm" href ="javascript:deleteUser(${user.id});" > 删除</a > </td > </tr > </c:forEach > </table > </form >
点击删除按钮提交表单,获取 id 按钮:
1 <a class ="btn btn-primary" href ="javascript:void(0);" id ="delSelected" > 删除选中</a >
js代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 window .onload = function ( ) { document .getElementById("delSelected" ).onclick = function ( ) { if (confirm("您确定要删除选中信息吗?" )){ var flag = false ; var cbs = document .getElementsByName("uid" ); for (var i = 0 ; i < cbs.length; i++) { if (cbs[i].checked){ flag = true ; break ; } } if (flag){ document .getElementById("form1" ).submit(); } } } document .getElementById("firstCb" ).onclick = function ( ) { var cbs = document .getElementsByName("uid" ); for (var i = 0 ; i < cbs.length; i++) { cbs[i].checked = this .checked; } } }
DelSelectedServlet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @WebServlet ("/delSelectedServlet" )public class DelSelectedServlet extends HttpServlet { protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] ids = request.getParameterValues("uid" ); UserSvice service = new UserServiceImpl(); service.delSelectedUser(ids); response.sendRedirect(request.getContextPath()+"/userListServlet" ); } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this .doPost(request, response); } }
Service 方法 1 2 3 4 5 6 7 8 @Override public void delSelectedUser (String[] ids) { for (String id : ids) { dao.delete(Integer.parseInt(id)); } }
dao方法 1 2 3 4 5 6 7 @Override public void delete (int id) { String sql = "delete from user where id = ?" ; template.update(sql,id); }