web_bookstore:基於 Servlet/JSP + HTML/CSS/JS 的輕量級網上書城,適合 Java Web 入門者串聯知識點。採用前後台分離架構,無框架依賴,核心邏輯清晰可控。
web_bookstore
├── src
│ ├── admin # 管理員 Servlet 控制邏輯
│ ├── dao # 實體類 + DAO 操作類
│ ├── demo # 測試用例
│ ├── service # 會員/業務 Servlet 控制邏輯
│ ├── util # 工具類(分頁、編碼過濾器等)
│ └── web.filter # 過濾器(字符編碼、登錄攔截)
└── WebContent
├── admin # 管理員 JSP 頁面
├── client # 會員前台 JSP 頁面
├── css/js/img # 靜態資源
└── util # 頁面片段(header、footer)
| 表名 | 核心欄位 | 說明 |
|---|---|---|
| user | id, username, password, email, status | 會員表,status=0 未激活,1 正常 |
| product | id, name, price, description, category_id, picture | 商品(書籍)表 |
| orders | id, user_id, total_price, address, receiver, phone, status, create_time | 訂單主表 |
| order_item | id, order_id, product_id, quantity, price | 訂單明細(單品) |
| message | id, user_id, content, create_time | 留言/通知表 |
SQL 建表腳本見專案 db.sql。
user,status=0。status=1。user_id 寫入 Cookie(名 user),Session 存放用戶對象。// AddCartServlet 關鍵邏輯
Cookie cookie = ServletUtils.getCookie(request, "user");
if (cookie == null) { /* 跳轉登錄 */ }
HttpSession session = request.getSession();
// 關鍵:Session 屬性名 = "cart" + user_id,實現用戶級隔離
Map<Product, Integer> cart = (Map<Product, Integer>) session.getAttribute("cart" + cookie.getValue());
if (cart == null) cart = new HashMap<>();
// 加入/更新數量
cart.put(product, cart.getOrDefault(product, 0) + 1);
session.setAttribute("cart" + cookie.getValue(), cart);
原理:同一 Session 對象對不同用戶存儲不同鍵,利用 Cookie 中的 user_id 做命名空間隔離。
OrderConfirmServlet 讀取 Session 購物車數據,轉向 client/order_confirm.jsp。CreateOrderServlet:PayServlet 更新訂單狀態 → 完成頁。user.role == admin。img/picture)。| 技術點 | 實現方式 | 學習價值 |
|---|---|---|
| 會話管理 | Cookie + Session,購物車鍵名隔離 | 多用戶狀態隔離核心模式 |
| 分頁查詢 | DAO 層 limit ?,? + Util 分頁 Bean | 大數據量前端分頁標準寫法 |
| 文件上傳 | Commons FileUpload / Servlet 3.0 @MultipartConfig | 圖片上傳實戰 |
| 過濾器鏈 | EncodingFilter + LoginFilter | 統一編碼、權限攔截 |
| MVC 分層 | Servlet(Controller) → Service → DAO → DB | 分層思想雛形,為 SpringMVC 鋪路 |
bookstore,執行 db.sql。db.properties(JDBC URL/用戶/密碼)。https://localhost:8080/web_bookstore/client/index.jsp。此專案雖簡單,但涵蓋了 Java Web 核心知識點的最小閉環,建議初學者完整跑通、逐行閱讀 Servlet 代碼,再逐步引入框架重構,理解框架解決的具體痛點。