购物车的实现(基于session)

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:;" οnclick="delProductByPid('${entry.value.product.pid }')" class="delete">删除</a>
								</td>
							</tr>
						</c:forEach>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值