1 首先封装与购物车有关的对象 2. 对象的封装 product.java略 **CartItem.java** public class CartItem { private Product product ; //购物项中购买的商品数量 private int buyNum ; //购物项小计 private double subTotal ; } **Cart.java** public class Cart { //存放CartItem对象在购物车中 private Map<String,CartItem> cartItem = new HashMap<String,CartItem>(); //存放商品总计 private double total ; } **Servlet代码** //通过pid将商品放入购物车Cart public void addProductToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); ProductService service = new ProductService(); //接收参数 商品id 购买该商品的数量 String pid = request.getParameter("pid"); int buyNum = Integer.parseInt(request.getParameter("buyNum")); /** * 接下来封装购物车Cart对象 */ //1 首先获得Product对象 Product product = service.findProductInfoByPid(pid); //2 获得CartItem对象 CartItem cartItem = new CartItem(); cartItem.setProduct(product); cartItem.setBuyNum(buyNum); //该商品小计为 double subTotal = product.getShop_price()*buyNum; cartItem.setSubTotal(subTotal); //3 封装目标对象------>购物车Cart 首先要判断在session中是否存在该购物车cart Cart cart = (Cart) session.getAttribute("cart"); //如果没有购物车cart就创建一个新购物车对象 if(cart==null) { cart = new Cart(); } //将购物项放到车中 key为商品的pid cart.getCartItem().put(pid, cartItem); //计算总计 double total = cart.getTotal()+subTotal; cart.setTotal(total); //将cart写回session中 session.setAttribute("cart", cart); //转发 刷新会出现总金额出错问题 //request.getRequestDispatcher("/cart.jsp").forward(request, response); //重定向 response.sendRedirect(request.getContextPath()+"/cart.jsp"); } **cart.jsp主要代码** <c:forEach items="${cart.cartItem }" var="entry"> <tr class="active"> <td width="60" width="40%"> <input type="hidden" name="id" value="22"> <img src="${pageContext.request.contextPath }/${entry.value.product.pimage}" width="70" height="60"> </td> <td width="30%"> <a target="_blank">${entry.value.product.pname}</a> </td> <td width="20%">¥${entry.value.product.shop_price}</td> <td width="10%"> ${entry.value.buyNum } </td> <td width="15%"> <span class="subtotal">¥${entry.value.subTotal}</span> </td> <td> <a href="javascript:;" onclick="delProductByPid('${entry.value.product.pid }')" class="delete">删除</a> </td> </tr> </c:forEach>
文章来源: 购物车的实现(基于session)