案例:实现在购物车中添加商品和删除购物车中指定商品的功能

一、向购物车中添加商品

1.1.创建AddCartServlet

public class AddCartServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.得到商品id
		String id = request.getParameter("id");
		// 2.调用service层方法,根据id查找商品
		ProductService service = new ProductService();
		try {
			Product p = service.findProductById(id);
			//3.将商品添加到购物车
			//3.1获得session对象
			HttpSession session = request.getSession();
			//3.2从session中获取购物车对象
			Map cart = (Map)session.getAttribute("cart");
			//3.3如果购物车为null,说明没有商品存储在购物车中,创建出购物车
			if (cart == null) {
				cart = new HashMap();
			}
			//3.4向购物车中添加商品
			Integer count = cart.put(p, 1);//returns: the previous value associated with key, or null if there was no mapping for key.
			//3.5如果商品数量不为空,则商品数量+1,否则添加新的商品信息
			if (count != null) {
				cart.put(p, count + 1);
			}			
			session.setAttribute("cart", cart);
			response.sendRedirect(request.getContextPath() + "/client/cart.jsp");
			return;
		} catch (FindProductByIdException e) {
			e.printStackTrace();
		}
	}
}

1.2.编写购物车页面cart.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="p" uri="http://www.itcast.cn/tag"%>



电子书城




	
	
	
	
首页     >    购物车
序号 商品名称 价格        数量 库存 小计 取消
${vs.count} ${entry.key.name } ${entry.key.price } ${entry.key.pnum} ${entry.key.price*entry.value} X
合计:  ${total}元
    

二、删除购物车中指定商品

案例:实现在购物车中添加商品和删除购物车中指定商品的功能_第1张图片

创建ChangeCartServlet

/**
 * 购物车内容变更
 * @author admin
 *
 */
public class ChangeCartServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.得到商品id
		String id = request.getParameter("id");
		// 2.得到要修改的数量
		int count = Integer.parseInt(request.getParameter("count"));
		// 3.从session中获取购物车.
		HttpSession session = request.getSession();
		Map cart = (Map) session.getAttribute("cart");
		Product p = new Product();
		p.setId(id);
		if (count != 0) {
			cart.put(p, count);
		} else {
			cart.remove(p);
		}
		response.sendRedirect(request.getContextPath() + "/client/cart.jsp");
		return;
	}
}

你可能感兴趣的:(javaweb,javaweb)