1 删除图书
1.1 修改 list.jsp
1.2 DAO
....
public void deleteBookById(String id) throws SQLException {
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
String sql = "delete from books where id = ?";
qr.update(sql,id);
}
1.3 Service
...
public void deleteBookById(String id) {
try {
bookDao.deleteBookById(id);
} catch (SQLException e) {
e.printStackTrace();
}
}
1.4 Servlet
@WebServlet("/DeleteBookByIdServlet")
public class DeleteBookByIdServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String id = req.getParameter("id");
BookServiceImpl bookService = new BookServiceImpl();
bookService.deleteBookById(id);
req.setAttribute("books",bookService.findAllBooks());
req.getRequestDispatcher("/admin/products/list.jsp").forward(req, resp);
}
}
2 删除添加提示
list.jsp
3 批量删除
3.1 list.jsp
- 添加批量删除按钮
function deleteAllBook() {
var checkboxs = document.getElementsByName('ckBookIds');
var ids = '';
for (var i = 0; i < checkboxs.length; i++) {
if (checkboxs[i].checked == true) {
ids += checkboxs[i].value + ",";
}
}
// 删除最后一个逗号
ids = ids.substring(0, ids.length - 1);
// 空字符串就不用删除了
if(ids == '') return;
location.href = '${pageContext.request.contextPath}/DeleteAllBookServlet?ids=' + ids;
}
3.2 DAO
public void deleteAllBook(String[] idsArr) throws SQLException {
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
String sql = "delete from books where id = ?";
// 方式1
//for (String id : idsArr) {
// qr.update(sql,id);
// }
Object[][] params = new Object[idsArr.length][];
for (int i = 0; i < idsArr.length; i++) {
params[i] = new Object[]{idsArr[i]};
}
qr.batch(sql, params);
}
3.3 Service
public void deleteAllBook(String ids) {
String[] idsArr = ids.split(",");
try {
bookDao.deleteAllBook(idsArr);
} catch (SQLException e) {
e.printStackTrace();
}
}
3.4 Servlet
@WebServlet("/DeleteAllBookServlet")
public class DeleteAllBookServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String ids = req.getParameter("ids");
System.out.println(ids);
BookServiceImpl bookService = new BookServiceImpl();
bookService.deleteAllBook(ids);
// 回到展示页面
req.setAttribute("books",bookService.findAllBooks());
req.getRequestDispatcher("/admin/products/list.jsp").forward(req, resp);
}
}
来源:CSDN
作者:一角残叶
链接:https://blog.csdn.net/u012292754/article/details/103791476