<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="com.test.bean.Goods,java.util.ArrayList" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>购物车</title> <style type="text/css"> table{border-collapse:collapse;} td{border:1px solid black; text-align:center; } #deal{margin-left:200px} </style> </head> <body> <jsp:useBean id="cart" class="com.test.bean.Cart" scope="session"></jsp:useBean> <%if(cart==null||cart.getGoodslist().size()==0) out.println("购物车空空如也.....<a href='index.jsp'>返回商品首页</a>"); else{ ArrayList<Goods>goodslist=cart.getGoodslist(); %> <div> 当前购物车共有<%=cart.getGcount() %>件物品 <a href='index.jsp'>返回商品首页</a><br> <table><tr> <td>序号</td> <td>商品号</td> <td>商品名称</td> <td>价格</td> <td>数量</td> <td>小计</td> <td>描述</td></tr> <%for(int i=0;i<goodslist.size();i++){ Goods goods=goodslist.get(i); %> <tr> <td><%=i+1 %></td> <td><%=goods.getGid() %></td> <td><%=goods.getGname() %></td> <td><%= String.format("%.2f", goods.getGprice())%></td> <td><%=goods.getGcount() %></td> <td><%=String.format("%.2f", goods.getGprice()*goods.getGcount()) %></td> <td><a href="<%=request.getContextPath() %>/Servlet/DelCartServlet?gid=<%=goods.getGid() %>">删除</a></td></tr> <%}%> </table><br> <span>总计</span><%=String.format("%.2f",cart.getTotal())%> <input type="button" id="deal" value="购买" /></input> </div> <%}%> <script type="text/javascript"> var dealbutton=document.getElementById("deal"); dealbutton.onclick=function(){ var cf=confirm("确定购买吗?"); if(cf==true){ window.location.href="Servlet/DealServlet"; } } </script> </body> </html> 修改删除功能,在购物车物品数量大于1的情况下点击“删除”时减少1个,等于1时删除此项商品;
时间: 2023-08-14 16:26:05 浏览: 338
要修改删除功能,在购物车物品数量大于1的情况下点击“删除”时,应该减少1个,等于1时则应该删除此项商品。具体实现的代码如下:
1. 在 DelCartServlet 中,判断商品数量是否大于1,若大于1,则减少1个;若等于1,则直接删除此商品。
```
int gid = Integer.parseInt(request.getParameter("gid"));
Cart cart = (Cart) request.getSession().getAttribute("cart");
ArrayList<Goods> goodslist = cart.getGoodslist();
for(int i = 0; i < goodslist.size(); i++) {
Goods goods = goodslist.get(i);
if(goods.getGid() == gid) {
if(goods.getGcount() > 1) {
goods.setGcount(goods.getGcount() - 1);
} else {
goodslist.remove(i);
}
break;
}
}
cart.setGoodslist(goodslist);
response.sendRedirect(request.getContextPath()+"/cart.jsp");
```
2. 在 cart.jsp 中,将删除按钮的链接修改为 DelCartServlet,并传递该商品的 gid 参数。
```
<td><a href="<%=request.getContextPath() %>/Servlet/DelCartServlet?gid=<%=goods.getGid() %>">删除</a></td>
```
阅读全文