在 JavaWeb 圖書商城開發中,購物車模組是連接用戶瀏覽與下單結算的關鍵橋梁。本文將深入剖析購物車的三種主流儲存方案,並提供完整的程式碼實作參考。
/** 購物車條目類 */
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 略...
}
/** 購物車類,使用 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>
BigDecimal 處理貨幣運算,避免浮點數精度問題
