購物車是電商系統核心模塊。本文通過完整代碼演示,詳細講解如何利用 HttpSession 存儲 Map<String, GoodsItem> 實現「加入購物車、數量疊加、頁面跳轉」核心流程,適合 Java Web 初學者快速掌握會話級狀態管理。
// 商品實體
public class Goods {
private String id;
private String name;
private double price;
// getter/setter...
}
// 購物車項:商品 + 數量
public class GoodsItem {
private Goods goods;
private int count;
public GoodsItem(Goods goods, int count) { ... }
// getter/setter...
}
public class PutCarServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1. 獲取商品 ID
String id = request.getParameter("goodsID");
// 2. 查詢商品完整信息
GoodsDAO dao = new GoodsDAO();
Goods g = dao.getGoodsByID(id);
// 3. 從 Session 獲取或創建購物車 Map
Map cart =
(Map) request.getSession().getAttribute("cart");
if (cart == null) {
cart = new HashMap();
}
// 4. 核心邏輯:已存在數量+1,否則新建項
if (cart.containsKey(id)) {
GoodsItem item = cart.get(id);
item.setCount(item.getCount() + 1); // 數量疊加
} else {
cart.put(id, new GoodsItem(g, 1)); // 新商品,數量=1
}
// 5. 更新 Session
request.getSession().setAttribute("cart", cart);
// 6. 重定向回商品列表繼續購物
response.sendRedirect("index.jsp");
}
}
| 技術點 | 實現方式 | 設計考量 |
|---|---|---|
| 會話隔離 | HttpSession 每用戶獨立 | 天然支援多用戶並發,無需手動管理 Session ID |
| 去重與疊加 | Map<商品ID, GoodsItem> | Key 唯一性天然去重,Value 封裝數量實現疊加 |
| 狀態持久化 | Session 默認內存存儲 | 生產環境建議改用 Redis/DB 持久化,支援集群與重啟不丟失 |
| 跳轉模式 | sendRedirect | 重定向避免表單重複提交,URL 顯示列表頁地址 |
<!-- 商品列表頁 index.jsp -->
<c:forEach items="${goodsList}" var="goods">
<tr>
<td>${goods.name}</td>
<td>${goods.price}</td>
<td>
<a href="PutCarServlet?goodsID=${goods.id}">加入購物車</a>
</td>
</tr>
</c:forEach>

點擊「加入購物車」後,商品自動加入 Session 購物車,頁面跳轉回列表,用戶可繼續瀏覽。
cart.values() 計算小計/總計UpdateCartServlet 處理 count 變更與 remove
src/
├─ com.entity // Goods, GoodsItem
├─ com.dao // GoodsDAO (JDBC/MyBatis)
├─ com.servlet // PutCarServlet, ListCartServlet...
└─ web/
├─ index.jsp
├─ cart.jsp
└─ WEB-INF/web.xml
掌握「Session + Map」這一核心模式,你就擁有了構建有狀態 Web 應用的基石。建議動手敲一遍代碼,並在瀏覽器開發者工具 Application → Cookies → JSESSIONID 觀察 Session ID 傳遞機制,深化對 HTTP 無狀態協議如何通過 Session 實現有狀態交互的理解。