使用Servlet实现批量删除

jsp文件

<form
					action="${pageContext.request.contextPath }/product/productRemoveBatch.action"
					method="post">
					<table class="table">
						<tr class="table_header">
							<td><input type="submit" value="删除选中" /></td>
...
</from>

Mapper文件

<!-- 批量删除 -->
	<delete id=</
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现图书的批量删除,你需要使用 JSP 与 Servlet 进行后台数据处理。以下是实现的步骤: 1. 在 JSP 页面中,创建一个表格用于显示所有图书信息,并在每行的最后一列添加一个复选框,用于选择需要删除的图书。 2. 在表格下方添加一个“删除”按钮,并使用 JavaScript 实现批量删除功能。当用户点击“删除”按钮时,遍历所有复选框,将被选中的图书的 ID 保存到一个数组中,并使用 Ajax 异步提交给 Servlet。 3. 在 Servlet 中,获取前台传来的图书 ID 数组,遍历数组并执行删除操作。 以下是代码示例: JSP 页面代码: ```html <form> <table> <thead> <tr> <th>ID</th> <th>书名</th> <th>作者</th> <th>出版社</th> <th>操作</th> </tr> </thead> <tbody> <% // 获取所有图书信息并显示在表格中 List<Book> bookList = BookDAO.getAllBooks(); for (Book book : bookList) { %> <tr> <td><%=book.getId()%></td> <td><%=book.getName()%></td> <td><%=book.getAuthor()%></td> <td><%=book.getPublisher()%></td> <td><input type="checkbox" name="bookIds" value="<%=book.getId()%>"></td> </tr> <%}%> </tbody> </table> <button type="button" onclick="deleteSelectedBooks()">删除</button> </form> <script> function deleteSelectedBooks() { var bookIds = []; var checkboxes = document.getElementsByName("bookIds"); for (var i = 0; i < checkboxes.length; i++) { if (checkboxes[i].checked) { bookIds.push(checkboxes[i].value); } } if (bookIds.length == 0) { alert("请选择要删除的图书"); return; } // 使用 Ajax 异步提交删除请求 var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); window.location.reload(); } }; xmlhttp.open("POST", "deleteBooksServlet?bookIds=" + bookIds.join(","), true); xmlhttp.send(); } </script> ``` Servlet 代码: ```java public class DeleteBooksServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] bookIds = request.getParameter("bookIds").split(","); for (String bookId : bookIds) { BookDAO.delete(Integer.parseInt(bookId)); } response.getWriter().write("删除成功"); } } ``` 在 Servlet 中,我们通过 `request.getParameter("bookIds")` 获取前台传来的图书 ID 数组,并通过 `String.split(",")` 方法将其转换为字符串数组。然后遍历数组,调用 `BookDAO.delete()` 方法进行删除操作。最后通过 `response.getWriter().write()` 返回删除结果给前台。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值