<a href="AddCart?id=${b.id}"><button class="btn btn-default">加入购物车<span class="glyphicon glyphicon-shopping-cart"></span></button></a>
商品详情页选中“加入购物车”后跳到AddCart
public class AddCart extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id=request.getParameter("id"); ProductService ps=new ProductService(); Book b=ps.findBookById(id); HttpSession session=request.getSession(); //从session中获取购物车对象 Map<Book,Integer> cart=(Map<Book,Integer>)session.getAttribute("cart"); //如果购物车为空,说明没有商品存储在购物车中,创建除购物车 if(cart==null) { cart=new HashMap<Book,Integer>() ; } //向购物车添加商品数量信息 Integer count=cart.put(b, 1); //如果商品数量不为空,则商品数量+1,否则添加新的商品信息 if(count!=null) { cart.put(b, count+1); } session.setAttribute("cart", cart); request.getRequestDispatcher("cart.jsp").forward(request, response);; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
以map集合存储Book对象还有购买数量,并且新建购物车,存进session中
<script type="text/javascript"> function changeNum(id,num,totalCount){ num = parseInt(num); totalCount =parseInt(totalCount); if(num<1){ if(confirm("是否确认要删除此商品?")){ num = 0; }else{ num=1; } } if(num>totalCount){ alert("购买数量不能大于库存数量!"); num=totalCount; } location.href="${pageContext.request.contextPath}/ChangeNumServlet?id="+id+"&num="+num; } </script>
public class ChangeNumServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); int num = Integer.parseInt(request.getParameter("num")); HttpSession session = request.getSession(); Map<Book, Integer> cart = (Map<Book, Integer>) session.getAttribute("cart"); ProductService ps=new ProductService(); Book b=ps.findBookById(id); //如果商品数据为0,就删除对象 if(num==0) { cart.clear(); }else { cart.clear(); cart.put(b, num); } request.getRequestDispatcher("cart.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }通过id找到对应的book对象后,从session中取出集合,要先清空集合再重新存键值(书和购买数量进去),不清空就会导致一会的cart页面出现多行从购物车里遍历取出来的数据
文章来源: jsp+servlet实现商城购物车功能