分析: 通过form表单传递数据,删除数据根据id编号删除。 前台 a class="btn btn-primary" href="javascript:void(0);" rel="external nofollow" id="delSelected"删除选中/a/divform id="form" action="${pageContext.request.
分析:
通过form表单传递数据,删除数据根据id编号删除。
前台
<a class="btn btn-primary" href="javascript:void(0);" rel="external nofollow" id="delSelected">删除选中</a> </div> <form id="form" 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> <td><input type="checkbox" name="uid" value="${user.id}"></td> <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}" rel="external nofollow" >修改</a> <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});" rel="external nofollow" >删除</a></td> </tr> </c:forEach> </table> </form>
Js
<script> function deleteUser(id) { //用户安全提示 if (confirm("您确定要删除吗?")){ //访问的路径 location.href=" ${pageContext.request.contextPath}/delUserServlet?id=" rel="external nofollow" +id; } } window.οnlοad=function () { //给删除选中按钮添加单击事件 document.getElementById("delSelected").οnclick=function () { if (confirm("您确定要删除选中条目吗?")) //表单提交 document.getElementById("form").submit(); } //1.获取第一个cb document.getElementById("firstCb").οnclick=function () { //获取下表所有的cb var cbs=document.getElementsByName("uid"); //遍历 for (var i=0;i<cbs.length;i++){ //设置这些cbs[i]的checked状态=firstCb.checked cbs[i].checked =this.checked; } } } </script>
后台
Servlet
@WebServlet("/delSelectedServlet") public class DelSelectedServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取所有id String[] ids=request.getParameterValues(“uid”); //调用service删除 UserService service=new UserServiceImpl(); service.delSelectedUser(ids); //跳转查询Servlet response.sendRedirect(request.getContextPath()+"/userListServlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
Service
public void delSelectedUser(String[] ids) { //遍历数组 for (String id:ids){ //调用dao删除 dao.deleteUser(Integer.parseInt(id)); } }
Dao
public void updateUser(User user) { String sql=“update userms set name=?,age=?,gender=?,address=?,qq=?,email=? where id=?”; template.update(sql,user.getName(),user.getAge(),user.getGender(),user.getAddress(),user.getQq(),user.getEmail(),user.getId()); }
总结
以上所述是小编给大家介绍的java实现选中删除功能的实例代码,希望对大家有所帮助!