(十七)将商品添加到购物车

需求:
    在商品详情页面上,输入购买的数量,点击加入购物车,在购物车页面上展示里面所有的商品
分析:
    涉及的实体:
        购物车 购物车项 商品
        购物车中的内容
            购物车项的map集合(map<商品的id,购物车项>)
            总金额
            
            add2Cart(购物车项)
            removeFromCart(String 商品的id)
            clearCart() 
        
        购物项中的内容
            商品对象
            购买数量
            小计
步骤分析:
    1.商品详情页面,输入购买的数量,点击加入购物车
        /store/cart?method=add&pid=??&count=??
    2.在cartservlet中的add方法操作
        先获取两个参数 pid    和 count
        调用ProductService 通过id获取一个商品
        拼装CartItem
            Product--通过service查询出来
            count--传递过来了
            suctotal--计算
    3.获取购物车,调用add2Cart(cartitem)
    4.页面跳转
        重定向 /jsp/cart.jsp

创建实体

  com.louis.domain.CartItem

  

package com.louis.domain;

import java.io.Serializable;
/**
 * 购物车项
 * @author Administrator
 *
 */
public class CartItem implements Serializable{
    private Product product;//商品对象
    private Integer    count;//购买数量
    private Double    subtotal=0.0;//小计
    
    public Product getProduct() {
        return product;
    }
    public void setProduct(Product product) {
        this.product = product;
    }
    public Integer getCount() {
        return count;
    }
    public void setCount(Integer count) {
        this.count = count;
    }
    public Double getSubtotal() {
        return product.getShop_price()*count;
    }
    
    public CartItem(Product product, Integer count) {
        this.product = product;
        this.count = count;
    }
    public CartItem() { }
    
    
    
}

com.louis.domain.Cart

package com.louis.domain;

import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public class Cart implements Serializable{
    //存放购物车项的集合  key:商品的id  cartitem:购物车项   使用map集合便于删除单个购物车项
    private Map<String, CartItem> map=new LinkedHashMap<>();
    
    //总金额
    private Double total=0.0;
    
    /**
     * 获取所有的购物车项,前端就能使用${cart.itmes }
     * @return
     */
    public Collection<CartItem> getItmes(){
        return  map.values();
    }
    /**
     * 添加到购物车
     * @param item 购物车项
     */
    public void add2Cart(CartItem item){
        //1.先判断购物车中有无该商品
        //1.1先获取商品的id
        String pid = item.getProduct().getPid();
        if(map.containsKey(pid)){
            ////设置购买数量 需要获取该商品之前的购买数量+现在的购买数量(item.getCount)
            //获取购物车中购物车项
            CartItem oItem = map.get(pid);
            oItem.setCount(oItem.getCount()+item.getCount());
        }else{
            //没有 将购物车项添加进去
            map.put(pid, item);
        }
        
        //2.添加完成之后 修改金额
        total+=item.getSubtotal();
    }
    
    /**
     *  从购物车删除指定购物车项
     * @param pid 商品的id
     */
    public void removeFromCart(String pid){
        //1.从集合中删除
        CartItem item = map.remove(pid);
        
        //2.修改金额
        total-=item.getSubtotal();
    }
    
    /**
     * 清空购物车
     */
    public void clearCart(){
        //1.map置空
        map.clear();
        
        //2.金额归零
        total=0.0;
    }
    
    

    public Map<String, CartItem> getMap() {
        return map;
    }

    public void setMap(Map<String, CartItem> map) {
        this.map = map;
    }

    public Double getTotal() {
        return total;
    }

    public void setTotal(Double total) {
        this.total = total;
    }
    
    
}

 com.louis.web.servlet.CartServlet

package com.louis.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.louis.domain.Cart;
import com.louis.domain.CartItem;
import com.louis.domain.Product;
import com.louis.service.ProductService;
import com.louis.utils.BeanFactory;


public class CartServlet extends BaseServlet {
    //因为remove、add都需要获取购物车,所以单独写个方法获取购物车
    public Cart getCart(HttpServletRequest request) {
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        //判断购物车是否为空
        if(cart == null) {
            //创建一个cart
            cart = new Cart();
            //添加到session域中
            request.getSession().setAttribute("cart", cart);
        }
        return cart;
    }

    public  String  add(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //1、获取pid和数量
        String pid = request.getParameter("pid");
        int count = Integer.parseInt(request.getParameter("count"));
        
        //2、调用productService通过pid获取一个商品
        ProductService productService = (ProductService) BeanFactory.getBean("ProductService");
        Product  product = productService.getByPid(pid);
        
        
        //3组装成cartitem
        CartItem cartItem = new CartItem(product, count);
        
        //4、添加到购物车中
        Cart cart = getCart(request);
        cart.add2Cart(cartItem);
        //5、重定向
        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
        return null;
    }
}

/store/WebContent/WEB-INF/web.xml

 <servlet>
    <description></description>
    <display-name>CartServlet</display-name>
    <servlet-name>CartServlet</servlet-name>
    <servlet-class>com.louis.web.servlet.CartServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CartServlet</servlet-name>
    <url-pattern>/cart</url-pattern>
  </servlet-mapping>

/store/WebContent/jsp/product_info.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!doctype html>
<html>

    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>会员登录</title>
        <link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css" type="text/css" />
        <script src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath}/js/bootstrap.min.js" type="text/javascript"></script>
        <!-- 引入自定义css文件 style.css -->
        <link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css" type="text/css" />

        <style>
            body {
                margin-top: 20px;
                margin: 0 auto;
            }
            
            .carousel-inner .item img {
                 100%;
                height: 300px;
            }
        </style>
    </head>

    <body>

        
            <!-- 动态包含 -->
    <jsp:include page="/jsp/head.jsp"></jsp:include>


        <div class="container">
            <div class="row">
                <div style="border: 1px solid #e4e4e4;930px;margin-bottom:10px;margin:0 auto;padding:10px;margin-bottom:10px;">
                    <a href="./index.htm">首页&nbsp;&nbsp;&gt;</a>
                    <a href="./蔬菜分类.htm">蔬菜&nbsp;&nbsp;&gt;</a>
                    <a>无公害蔬菜</a>
                </div>

                <div style="margin:0 auto;950px;">
                    <div class="col-md-6">
                        <img style="opacity: 1;400px;height:350px;" title="" class="medium" src="${pageContext.request.contextPath}/${bean.pimage}">
                    </div>

                    <div class="col-md-6">
                        <form id="formId" action="${pageContext.request.contextPath }/cart?method=add" method="post">
                            <input type="hidden" name="pid" value="${bean.pid }">
                            <div><strong>${bean.pname }</strong></div>
                            <div style="border-bottom: 1px dotted #dddddd;350px;margin:10px 0 10px 0;">
                                <div>编号:${bean.pid }</div>
                            </div>
    
                            <div style="margin:10px 0 10px 0;">商城价: <strong style="color:#ef0101;">¥:${bean.shop_price }元/份</strong> 参 考 价: <del>¥${bean.market_price }元/份</del>
                            </div>
    
                            <div style="margin:10px 0 10px 0;">促销: <a target="_blank" title="限时抢购 (2014-07-30 ~ 2015-01-01)" style="background-color: #f07373;">限时抢购</a> </div>
    
                            <div style="padding:10px;border:1px solid #e7dbb1;330px;margin:15px 0 10px 0;;background-color: #fffee6;">
                                <div style="margin:5px 0 10px 0;">白色</div>
    
                                <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">购买数量:
                                    <input id="quantity" name="count" value="1" maxlength="4" size="10" type="text"> </div>
                                <div style="margin:20px 0 10px 0;;text-align: center;">
                                    <a href="javascript:void(0)" onclick="addCart()">
                                        <input style="background: url('${pageContext.request.contextPath}/images/product.gif') no-repeat scroll 0 -600px rgba(0, 0, 0, 0);height:36px;127px;" value="加入购物车" type="button">
                                    </a> &nbsp;收藏商品</div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="clear"></div>
                <div style="950px;margin:0 auto;">
                    <div style="background-color:#d3d3d3;930px;padding:10px 10px;margin:10px 0 10px 0;">
                        <strong>商品介绍</strong>
                    </div>

                    <div>
                        ${bean.pdesc }
                    </div>

                    <div style="background-color:#d3d3d3;930px;padding:10px 10px;margin:10px 0 10px 0;">
                        <strong>商品参数</strong>
                    </div>
                    <div style="margin-top:10px;900px;">
                        <table class="table table-bordered">
                            <tbody>
                                <tr class="active">
                                    <th colspan="2">基本参数</th>
                                </tr>
                                <tr>
                                    <th width="10%">级别</th>
                                    <td width="30%">标准</td>
                                </tr>
                                <tr>
                                    <th width="10%">标重</th>
                                    <td>500</td>
                                </tr>
                                <tr>
                                    <th width="10%">浮动</th>
                                    <td>200</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div style="background-color:#d3d3d3;900px;">
                        <table class="table table-bordered">
                            <tbody>
                                <tr class="active">
                                    <th><strong>商品评论</strong></th>
                                </tr>
                                <tr class="warning">
                                    <th>暂无商品评论信息 <a>[发表商品评论]</a></th>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div style="background-color:#d3d3d3;900px;">
                        <table class="table table-bordered">
                            <tbody>
                                <tr class="active">
                                    <th><strong>商品咨询</strong></th>
                                </tr>
                                <tr class="warning">
                                    <th>暂无商品咨询信息 <a>[发表商品咨询]</a></th>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
        </div>

        <div style="margin-top:50px;">
            <img src="${pageContext.request.contextPath}/image/footer.jpg" width="100%" height="78" alt="我们的优势" title="我们的优势" />
        </div>

        <div style="text-align: center;margin-top: 5px;">
            <ul class="list-inline">
                <li><a>关于我们</a></li>
                <li><a>联系我们</a></li>
                <li><a>招贤纳士</a></li>
                <li><a>法律声明</a></li>
                <li><a>友情链接</a></li>
                <li><a target="_blank">支付方式</a></li>
                <li><a target="_blank">配送方式</a></li>
                <li><a>服务声明</a></li>
                <li><a>广告声明</a></li>
            </ul>
        </div>
        <div style="text-align: center;margin-top: 5px;margin-bottom:20px;">
            Copyright &copy; 2005-2016 传智商城 版权所有
        </div>

    </body>
    <script type="text/javascript">
        function addCart(){
            //将表单提交
            document.getElementById("formId").submit();
        }
    </script>
</html>

/store/WebContent/jsp/cart.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html>

    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>会员登录</title>
        <link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css" type="text/css" />
        <script src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath}/js/bootstrap.min.js" type="text/javascript"></script>
        <!-- 引入自定义css文件 style.css -->
        <link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css" type="text/css" />
        <style>
            body {
                margin-top: 20px;
                margin: 0 auto;
            }
            
            .carousel-inner .item img {
                 100%;
                height: 300px;
            }
            
            .container .row div {
                /* position:relative;
     float:left; */
            }
            
            font {
                color: #3164af;
                font-size: 18px;
                font-weight: normal;
                padding: 0 10px;
            }
        </style>
    </head>

    <body>

        <!-- 动态包含 -->
    <jsp:include page="/jsp/head.jsp"></jsp:include>

        <div class="container">
            <c:if test="${empty cart.map }">
                <h1>购物车空空如也~~赶紧逛逛去!!</h1>
            </c:if>
            <c:if test="${not empty cart.map }">
                <div class="row">
                    
                    <div style="margin:0 auto; margin-top:10px;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>
                                <c:forEach items="${cart.itmes }" var="item">
                                    <tr class="active">
                                        <td width="60" width="40%">
                                            <input type="hidden" name="id" value="22">
                                            <img src="${pageContext.request.contextPath}/${item.product.pimage}" width="70" height="60">
                                        </td>
                                        <td width="30%">
                                            <a target="_blank">${item.product.pname }</a>
                                        </td>
                                        <td width="20%">
                                            ¥${item.product.shop_price }
                                        </td>
                                        <td width="10%">
                                            <input type="text" name="quantity" value="${item.count }" maxlength="4" size="10" readonly="readonly">
                                        </td>
                                        <td width="15%">
                                            <span class="subtotal">¥${item.subtotal }</span>
                                        </td>
                                        <td>
                                            <a href="javascript:void(0);" class="delete" onclick="removeFromCart('${item.product.pid}')">删除</a>
                                        </td>
                                    </tr>
                                </c:forEach>
                            </tbody>
                        </table>
                    </div>
                    
                </div>
    
                <div style="margin-right:130px;">
                    <div style="text-align:right;">
                        <em style="color:#ff6600;">
                    登录后确认是否享有优惠&nbsp;&nbsp;
                </em> 赠送积分: <em style="color:#ff6600;">596</em>&nbsp; 商品金额: <strong style="color:#ff6600;">¥${cart.total }元</strong>
                    </div>
                    <div style="text-align:right;margin-top:10px;margin-bottom:10px;">
                        <a href="${pageContext.request.contextPath }/cart?method=clear" id="clear" class="clear">清空购物车</a>
                        <a href="${pageContext.request.contextPath }/order?method=add">
                            <input type="submit" width="100" value="提交订单" name="submit" border="0" style="background: url('${pageContext.request.contextPath}/images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0);
                            height:35px;100px;color:white;">
                        </a>
                    </div>
                </div>
            </c:if>
        </div>

        <div style="margin-top:50px;">
            <img src="${pageContext.request.contextPath}/image/footer.jpg" width="100%" height="78" alt="我们的优势" title="我们的优势" />
        </div>

        <div style="text-align: center;margin-top: 5px;">
            <ul class="list-inline">
                <li><a>关于我们</a></li>
                <li><a>联系我们</a></li>
                <li><a>招贤纳士</a></li>
                <li><a>法律声明</a></li>
                <li><a>友情链接</a></li>
                <li><a target="_blank">支付方式</a></li>
                <li><a target="_blank">配送方式</a></li>
                <li><a>服务声明</a></li>
                <li><a>广告声明</a></li>
            </ul>
        </div>
        <div style="text-align: center;margin-top: 5px;margin-bottom:20px;">
            Copyright &copy; 2005-2016 传智商城 版权所有
        </div>

    </body>
    <script type="text/javascript">
        function removeFromCart(pid){
            if(confirm("您确认狠心要丢弃我吗?")){
                location.href="${pageContext.request.contextPath}/cart?method=remove&pid="+pid;
            }
        }
    </script>
</html>

效果:

 

问题

map集合的使用

原文地址:https://www.cnblogs.com/Michael2397/p/7659360.html