首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

JavaWeb 圖書商城購物車模組深度解析:Session、Cookie 與資料庫儲存策略

     編輯:Java 相關知識

購物車模組核心架構設計

在 JavaWeb 圖書商城開發中,購物車模組是連接用戶瀏覽與下單結算的關鍵橋梁。本文將深入剖析購物車的三種主流儲存方案,並提供完整的程式碼實作參考。

三大儲存策略對比

  • Session 儲存:伺服器端記憶體存放,安全性高,但叢集環境需共享 Session
  • Cookie 儲存:客戶端瀏覽器存放,減輕伺服器壓力,但容量有限(4KB)且安全性較低
  • 資料庫儲存:持久化保存,支援跨裝置同步,適合已登入用戶,但增加資料庫負載

核心類別設計

CartItem - 購物車條目

/** 購物車條目類 */
public class CartItem {
    private Book book;    // 商品資訊
    private int count;    // 購買數量

    /** 計算小計,使用 BigDecimal 避免浮點數精度誤差 */
    public double getSubtotal() {
        BigDecimal price = new BigDecimal(String.valueOf(book.getPrice()));
        BigDecimal quantity = new BigDecimal(String.valueOf(count));
        return price.multiply(quantity).doubleValue();
    }
    // getter/setter 略...
}

Cart - 購物車主體

/** 購物車類,使用 LinkedHashMap 保持插入順序 */
public class Cart {
    private Map items = new LinkedHashMap<>();

    /** 計算總金額 */
    public double getTotal() {
        BigDecimal total = BigDecimal.ZERO;
        for (CartItem item : items.values()) {
            total = total.add(new BigDecimal(String.valueOf(item.getSubtotal())));
        }
        return total.doubleValue();
    }

    /** 添加商品:若已存在則累加數量 */
    public void add(CartItem cartItem) {
        String bid = cartItem.getBook().getBid();
        if (items.containsKey(bid)) {
            CartItem existing = items.get(bid);
            existing.setCount(existing.getCount() + cartItem.getCount());
        } else {
            items.put(bid, cartItem);
        }
    }

    /** 刪除指定商品 */
    public void delete(String bid) {
        items.remove(bid);
    }

    /** 清空購物車 */
    public void clear() {
        items.clear();
    }

    /** 獲取所有條目 */
    public Collection getCartItems() {
        return items.values();
    }
}

前端整合示例

配合 JSTL 標籤庫實現購物車列表頁面:

<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="https://java.sun.com/jsp/jstl/fmt" %>
<table>
    <c:forEach items="${cart.cartItems}" var="item">
        <tr>
            <td><c:out value="${item.book.bname}"/></td>
            <td><fmt:formatNumber value="${item.book.price}" type="currency"/></td>
            <td><c:out value="${item.count}"/></td>
            <td><fmt:formatNumber value="${item.subtotal}" type="currency"/></td>
            <td><a href="CartServlet?action=delete&bid=${item.book.bid}">移除</a></td>
        </tr>
    </c:forEach>
    <tr>
        <td colspan="3">總計</td>
        <td><fmt:formatNumber value="${cart.total}" type="currency"/></td>
    </tr>
</table>

最佳實踐建議

  1. 未登入用戶:優先使用 Session 儲存,簡單高效
  2. 已登入用戶:採用資料庫持久化,支援多裝置同步購物車
  3. 混合策略:Session 快取 + 定期同步至資料庫,平衡效能與資料安全
  4. 金額計算:務必使用 BigDecimal 處理貨幣運算,避免浮點數精度問題

購物車流程圖

刪除操作示意

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved