package servlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import entity.Cart;
import entity.Product;
public class AddCartServlet extends HttpServlet{
public AddCartServlet(){
super();
}
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
doPost(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
HttpSession session = request.getSession(false);
RequestDispatcher dispatcher;
//如果session不存在,转到浏览商品页面
if(session == null){
dispatcher = request.getRequestDispatcher("/jsp/ShowSingleProduct.jsp");
dispatcher.forward(request, response);
}
//从session中取出购物车和要添加的商品;
Map cart =(Map) session.getAttribute("cart");
Product product = (Product) session.getAttribute("product");
//如果购物车不存在,创建购物车
if(cart == null){
//将购物车存入session中
cart = new HashMap();
session.setAttribute("cart", cart);
}
//从购物车中根据商品编号取出相应的商品项对象(如果有,数量加一;否则创建商品项)
Cart cartItem = (Cart)cart.get(product.getProduct_no());
if(cartItem != null){
cartItem.setQuantity(cartItem.getQuantity() +1);
}
else{
Cart cartItem1 = new Cart();
cartItem1.setProduct(product);
cartItem1.setQuantity(1);
cart.put(product.getProduct_no(), cartItem1);
}
response.sendRedirect("../JSP/ShowCart.jsp");
}
}
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.util.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="entity.Product" %>
<html>
<body>
<table cellSpacing=1 cellPadding=2 Width=490 border=1>
<thead>
<tr align="center">
<th>商品图片</th><th>商品名称</th><th>商品介绍</th><th>商品价格</th><th>商品数量</th><th>小计</th>
</tr>
</thead>
<c:if test="${empty cart}">
<tr colspan="4" align="center">购物车当前为空</tr>
</c:if>
<c:if test="${not empty cart}">
<c:set var="total" value="0"/>
<c:forEach items = "${cart}" var = "item">
<tr>
<td>${item.value.product['product_picture']}</td>
<td>${item.value.product['product_name']}</td>
<td>${item.value.product['product_introduct']}</td>
<td>${item.value.product['product_price']}</td>
<td>${item.value.quantity}</td>
<td>${item.value.quantity*item.value.product['product_price']}</td>
</tr>
<c:set var="total" value="${total+item.value.quantity*item.value.product['product_price']}"/>
</c:forEach>
<td colspan="5"align="right">总价</td><td>${total}</td>
</c:if>
</table>
<br>
<a href="#">继续购物</a>
<form method="get"action="">
</form>
</body>
</html>