1首先在前台jsp页面设置好删除按钮:为按钮绑定一个事件delProduct(pid),参数为商品的pid,处理页面交由pattern为adminDelProduct的servlet处理。
list.jsp
function delProduct(pid) { //alert(); var isDel = confirm("您确定要删除吗?") if(isDel){ //要删除 location.href = "${pageContext.request.contextPath}/adminDelProduct?pid="+pid; } }
<td align="center" style="HEIGHT: 22px"> <a href="javascript:void(0)" οnclick="delProduct('${pro.pid}')"> 删除 </a> </td>
2其次在web层的servlet文件中,获取要删除商品的pid,然后将pid传递到service层。
AdminDelProductServlet.java
@WebServlet(name = "AdminDelProductServlet", urlPatterns = {"/adminDelProduct"}) public class AdminDelProductServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取要删除的pid String pid = request.getParameter("pid"); //传递pid到service层 AdminProductService service = new AdminProductService(); try { service.delProductByPid(pid); } catch (SQLException e) { e.printStackTrace(); } response.sendRedirect(request.getContextPath()+"/adminProductList"); } }
3然后在service层的service文件中,组合一个对应的dao对象,并调用该对象的delProductById()方法,根据pid删除商品
AdminProductService.java
public void delProductByPid(String pid) throws SQLException { AdminProductDao dao = new AdminProductDao(); dao.delProductByPid(pid); }
4接着在dao层的dao文件中,执行具体的数据库添加商品操作;根据pid删除商品。
AdminProductDao.java
public void delProductByPid(String pid) throws SQLException { QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "delete from product where pid=?"; runner.update(sql,pid); }
5最后在web层的servlet中采用重定向的方法跳转至adminProductList的servlet进行商品的展示(代码见步骤2)。