天天看點

圖書商城:購物車子產品購物車存儲1、建立相關類2、添加購物車條目3、清空條目4、删除購物車條目5、我的購物車

購物車存儲

  • 儲存在session中
  • 儲存在cookie中
  • 儲存在資料庫中

1、建立相關類

購物車的結構:

  • CartItem:購物車條目,包含圖書和數量
  • Cart:購物車,包含一個Map
/**
 * 購物車類
 */
public class Cart {
    private Map<String,CartItem> map = new LinkedHashMap<String,CartItem>();

    /**
     * 計算合計
     * @return
     */
    public double getTotal() {
        // 合計=所有條目的小計之和
        BigDecimal total = new BigDecimal("0");
        for(CartItem cartItem : map.values()) {
            BigDecimal subtotal = new BigDecimal("" + cartItem.getSubtotal());
            total = total.add(subtotal);
        }
        return total.doubleValue();
    }

    /**
     * 添加條目到車中
     * @param cartItem
     */
    public void add(CartItem cartItem) {
        if(map.containsKey(cartItem.getBook().getBid())) {//判斷原來車中是否存在該條目
            CartItem _cartItem = map.get(cartItem.getBook().getBid());//傳回原條目
            _cartItem.setCount(_cartItem.getCount() + cartItem.getCount());//設定老條目的數量為,其自己數量+新條目的數量
            map.put(cartItem.getBook().getBid(), _cartItem);
        } else {
            map.put(cartItem.getBook().getBid(), cartItem);
        }
    }

    /**
     * 清空所有條目
     */
    public void clear() {
        map.clear();
    }

    /**
     * 删除指定條目
     * @param bid
     */
    public void delete(String bid) {
        map.remove(bid);
    }

    /**
     * 擷取所有條目
     * @return
     */
    public Collection<CartItem> getCartItems() {
        return map.values();
    }
}
           
/**
 * 購物車條目類
 * 
 */
public class CartItem {
    private Book book;// 商品
    private int count;// 數量

    /**
     * 小計方法
     * @return
     * 處理了二進制運算誤差問題
     */
    public double getSubtotal() {//小計方法,但它沒有對應的成員!
        BigDecimal d1 = new BigDecimal(book.getPrice() + "");
        BigDecimal d2 = new BigDecimal(count + "");
        return d1.multiply(d2).doubleValue();
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}
           

2、添加購物車條目

圖書商城:購物車子產品購物車存儲1、建立相關類2、添加購物車條目3、清空條目4、删除購物車條目5、我的購物車
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>購物車清單</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css" target="_blank" rel="external nofollow" >
    -->
<style type="text/css">
    * {
        font-size: pt;
    }
    div {
        margin:px;
        border: solid px gray;
        width: px;
        height: px;
        text-align: center;
    }
    li {
        margin: px;
    }

    #buy {
        background: url(<c:url value='/images/all.png'/>) no-repeat;
        display: inline-block;

        background-position:  -px;
        margin-left: px;
        height: px;
        width: px;
    }
    #buy:HOVER {
        background: url(<c:url value='/images/all.png'/>) no-repeat;
        display: inline-block;

        background-position:  -px;
        margin-left: px;
        height: px;
        width: px;
    }
</style>
  </head>

  <body>
<h1>購物車</h1>
<c:choose>
    <%-- 如果沒有車,或車的内容集合為長 --%>
    <c:when test="${empty sessionScope.cart or fn:length(sessionScope.cart.cartItems) eq 0}">
        <img src="<c:url value='/images/cart.png'/>" width="300"/>
    </c:when>
    <c:otherwise>
<table border="1" width="100%" cellspacing="0" background="black">
    <tr>
        <td colspan="7" align="right" style="font-size: 15pt; font-weight: 900">
            <a href="<c:url value='/CartServlet?method=clear'/>">清空購物車</a>
        </td>
    </tr>
    <tr>
        <th>圖檔</th>
        <th>書名</th>
        <th>作者</th>
        <th>單價</th>
        <th>數量</th>
        <th>小計</th>
        <th>操作</th>
    </tr>

<c:forEach items="${sessionScope.cart.cartItems }" var="cartItem">
    <tr>
        <td><div><img src="<c:url value='/${cartItem.book.image }'/>"/></div></td>
        <td>${cartItem.book.bname }</td>
        <td>${cartItem.book.author }</td>
        <td>${cartItem.book.price }元</td>
        <td>${cartItem.count }</td>
        <td>${cartItem.subtotal }元</td>
        <td><a href="<c:url value='/CartServlet?method=delete&bid=${cartItem.book.bid }'/>">删除</a></td>
    </tr>
</c:forEach>

    <tr>
        <td colspan="7" align="right" style="font-size: 15pt; font-weight: 900">
            合計:${sessionScope.cart.total }元
        </td>
    </tr>
    <tr>
        <td colspan="7" align="right" style="font-size: 15pt; font-weight: 900">
            <a id="buy" href="<c:url value='/OrderServlet?method=add'/>"></a>
        </td>
    </tr>
</table>
    </c:otherwise>
</c:choose>
  </body>
</html>
           
public class CartServlet extends BaseServlet {
    /**
     * 添加購物條目
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String add(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /*
         * 1. 得到車
         * 2. 得到條目(得到圖書和數量)
         * 3. 把條目添加到車中
         */
        /*
         * 1. 得到車
         */
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        /*
         * 表單傳遞的隻有bid和數量
         * 2. 得到條目
         *   > 得到圖書和數量
         *   > 先得到圖書的bid,然後我們需要通過bid查詢資料庫得到Book
         *   > 數量表單中有
         */
        String bid = request.getParameter("bid");
        Book book = new BookService().load(bid);
        int count = Integer.parseInt(request.getParameter("count"));
        CartItem cartItem = new CartItem();
        cartItem.setBook(book);
        cartItem.setCount(count);

        /*
         * 3. 把條目添加到車中
         */
        cart.add(cartItem);

        return "f:/jsps/cart/list.jsp";
    }

    /**
     * 清空購物條目
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String clear(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /**
         * 1. 得到車
         * 2. 設定車的clear
         */
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        cart.clear();
        return "f:/jsps/cart/list.jsp";
    }

    /**
     * 删除購物條目
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String delete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /*
         * 1. 得到車
         * 2. 得到要删除的bid
         */
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        String bid = request.getParameter("bid");
        cart.delete(bid);
        return "f:/jsps/cart/list.jsp";
    }
}
           

3、清空條目

圖書商城:購物車子產品購物車存儲1、建立相關類2、添加購物車條目3、清空條目4、删除購物車條目5、我的購物車

4、删除購物車條目

圖書商城:購物車子產品購物車存儲1、建立相關類2、添加購物車條目3、清空條目4、删除購物車條目5、我的購物車

5、我的購物車

top.jsp中存在一個連結:我的購物車

我的購物車直接通路/jsps/cart/list.jsp,它會顯示session中車的所有條目

繼續閱讀