day03 --serlet的抽取 购物车显示 删除单个商品 清空购物车
servlet的抽取
public class BaseServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); try { //1.获得请求的method名称 String methodName = req.getParameter("method"); //2.获得当前被访问的字节码对象 Class<? extends BaseServlet> clazz = this.getClass(); //3.获得当前字节码对象中指定的方法 Method method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); //4.执行相应功能方法 method.invoke(this, req,resp); } catch (Exception e) { e.printStackTrace(); } } }
购物车相关
Cart
public class Cart { //该购物车中存储的n个购物项 private Map<String,CartItem> cartItems = new HashMap<String,CartItem>(); //商品总计 private double total; public Map<String, CartItem> getCartItems() { return cartItems; } public void setCartItems(Map<String, CartItem> cartItems) { this.cartItems = cartItems; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } }
CartItem
public class CartItem { private Product product; private int buyNum; private double subtotal; public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public int getBuyNum() { return buyNum; } public void setBuyNum(int buyNum) { this.buyNum = buyNum; } public double getSubtotal() { return subtotal; } public void setSubtotal(double subtotal) { this.subtotal = subtotal; } }
Product
public class Product { private String pid; private String pname; private double market_price; private double shop_price; private String pimage; private Date pdate; private int is_hot; private String pdesc; private int pflag; //cid外键,直接引用对象 private Category category; public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public double getMarket_price() { return market_price; } public void setMarket_price(double market_price) { this.market_price = market_price; } public double getShop_price() { return shop_price; } public void setShop_price(double shop_price) { this.shop_price = shop_price; } public String getPimage() { return pimage; } public void setPimage(String pimage) { this.pimage = pimage; } public Date getPdate() { return pdate; } public void setPdate(Date pdate) { this.pdate = pdate; } public int getIs_hot() { return is_hot; } public void setIs_hot(int is_hot) { this.is_hot = is_hot; } public String getPdesc() { return pdesc; } public void setPdesc(String pdesc) { this.pdesc = pdesc; } public int getPflag() { return pflag; } public void setPflag(int pflag) { this.pflag = pflag; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } @Override public String toString() { return "Product [pid=" + pid + ", pname=" + pname + ", market_price=" + market_price + ", shop_price=" + shop_price + ", pimage=" + pimage + ", pdate=" + pdate + ", is_hot=" + is_hot + ", pdesc=" + pdesc + ", pflag=" + pflag + ", category=" + category + "]"; } }
ProductServlet
public class ProductServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); //获得请求的方法 String methodName = request.getParameter("method"); if("productList".equals(methodName)){ productList(request,response); }else if("categoryList".equals(methodName)){ categoryList(request,response); }else if("index".equals(methodName)){ index(request,response); }else if("productInfo".equals(methodName)){ productInfo(request,response); }else if("addProductToCart".equals(methodName)){ addProductToCart(request,response); }else if("delProFromCart".equals(methodName)){ delProFromCart(request,response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } //添加商品到购物车 public void addProductToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ HttpSession session = request.getSession(); ProductService service = new ProductService(); //获得要放到购物车的pid String pid = request.getParameter("pid"); //获得该商品的购买输量 int buyNum = Integer.parseInt(request.getParameter("buyNum")); //获得product对象 Product product = service.findProductByPid(pid); //计算小计 double subtotal = product.getShop_price()*buyNum; //封装成CartItem CartItem item = new CartItem(); item.setBuyNum(buyNum); item.setProduct(product); item.setSubtotal(subtotal); //获得购物车--判断是否在session中已经存在购物车 Cart cart = (Cart) session.getAttribute("cart"); if(cart == null){ //第一次访问,没有cart,新建 cart = new Cart(); } //将购物项放到购物车中--key是pid //先判断购物车总是否已经包含此购物项了-- 判断key是否已经存在 //如果购物车中已经存在该商品--将现在购买的数量与原有的数量相加 Map<String, CartItem> cartItems = cart.getCartItems(); if(cartItems.containsKey(pid)){ //取出原有的商品数量 CartItem cartItem = cartItems.get(pid); int oldBuyNum = cartItem.getBuyNum(); oldBuyNum+=buyNum; cartItem.setBuyNum(oldBuyNum); cart.setCartItems(cartItems); //修改小计 //小计=数量*单价 cartItem.setSubtotal(oldBuyNum*product.getShop_price()); }else{ //如果购物车中没有该商品 cartItems.put(pid, item); } //计算总计 //原先的总价+这次的小计 double total = cart.getTotal()+subtotal; cart.setTotal(total); //将车再次访问session session.setAttribute("cart", cart); //直接跳转到购物车页面 //请求转发和重定向的区别在此,如果用请求转发,地址不发生 变化,再次刷新,重新访问一次servlet,数量发生变化。实际上不应该变化,所以用重定向 //request.getRequestDispatcher("cart.jsp").forward(request, response); response.sendRedirect(request.getContextPath()+"/cart.jsp"); } //删除一个购物项 public void delProFromCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String pid = request.getParameter("pid"); //删除session中的购物车中的购物项集合中的item HttpSession session = request.getSession(); Cart cart = (Cart) session.getAttribute("cart"); if(cart != null){ Map<String, CartItem> cartItems = cart.getCartItems(); //需要修改总价 cart.setTotal(cart.getTotal()-cartItems.get(pid).getSubtotal()); cartItems.remove(pid); } session.setAttribute("cart", cart); //跳转回购物车页面 response.sendRedirect(request.getContextPath()+"/cart.jsp"); } //清空购物车 public void clearCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ HttpSession session = request.getSession(); session.removeAttribute("cart"); response.sendRedirect(request.getContextPath()+"/cart.jsp"); } }
cart.jsp
<!-- 判断购物车中是否还有商品 --> <c:if test="${!empty cart.cartItems }"> <div class="container"> <div class="row"> <div style="margin:0 auto; margin-top:10px;width:950px;"> <strong style="font-size:16px;margin:5px 0;">订单详情</strong> <table class="table table-bordered"> <tbody> <tr class="warning"> <th>图片</th> <th>商品</th> <th>价格</th> <th>数量</th> <th>小计</th> <th>操作</th> </tr> <!-- map的遍历 --> <c:forEach items="${cart.cartItems }" 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:void(0);" onclick="delProFromCart('${entry.value.product.pid}')" class="delete">删除</a> </td> </tr> </c:forEach> </tbody> </table> </div> </div> <div style="margin-right:130px;"> <div style="text-align:right;"> <em style="color:#ff6600;"> 登录后确认是否享有优惠 </em> 赠送积分: <em style="color:#ff6600;">596</em> 商品金额: <strong style="color:#ff6600;">${cart.total }元 </strong> </div> <div style="text-align:right;margin-top:10px;margin-bottom:10px;"> <a href="javascript:void(0)" onlick="clearCart();" id="clear" class="clear">清空购物车</a> <a href="order_info.htm"> <input type="submit" width="100" value="提交订单" name="submit" border="0" style="background: url('./images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0); height:35px;width:100px;color:white;"> </a> </div> </div> </div> </c:if> <c:if test="${empty cart.cartItems }"> <div> <img alt="" src="${pageContext.request.contextPath}/images/cart-empty.png"> <a href="${pageContext.request.contextPath }/index">返回首页</a> </div> </c:if>