(十七)將商品添加到購物車


需求:
    在商品詳情頁面上,輸入購買的數量,點擊加入購物車,在購物車頁面上展示里面所有的商品
分析:
    涉及的實體:
        購物車 購物車項 商品
        購物車中的內容
            購物車項的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 {
                width: 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;width: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;width:950px;">
                    <div class="col-md-6">
                        <img style="opacity: 1;width: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;width: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;width: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;width:127px;" value="加入購物車" type="button">
                                    </a> &nbsp;收藏商品</div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="clear"></div>
                <div style="width:950px;margin:0 auto;">
                    <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;">
                        <strong>商品介紹</strong>
                    </div>

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

                    <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;">
                        <strong>商品參數</strong>
                    </div>
                    <div style="margin-top:10px;width: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;width: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;width: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 {
                width: 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;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>
                                <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;width: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集合的使用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM