jsp+servlet实现商城购物车功能

商品详情页选中“加入购物车”后跳到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 cart=(Map)session.getAttribute("cart");
		//如果购物车为空,说明没有商品存储在购物车中,创建除购物车
		if(cart==null) {
			cart=new HashMap() ;	
		}
		//向购物车添加商品数量信息
		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中

 

 

 序号  商品名称 价格  数量 库存 小计 取消
${vs.count} ${entry.key.name} ${entry.key.price } ${entry.key.pnum} ${entry.key.price*entry.value} X

合计:  ${total}元



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 cart = (Map) 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页面出现多行从购物车里遍历取出来的数据
 

你可能感兴趣的:(java,ee)