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

JavaWeb 圖書商城實戰(四):圖書模塊完整實現 (CRUD、分類查詢、詳情加載)

     編輯:Java 相關知識

模塊職責

圖書模塊是商城核心,包含圖書的增刪改查、按分類查詢、詳情頁加載、庫存管理等功能。關聯分類表,支持圖片展示。

一、領域模型

public class Book {
    private String bid;       // 圖書 ID
    private String bname;     // 書名
    private double price;     // 價格
    private String author;    // 作者
    private String image;     // 封面圖片路徑
    private Category category; // 所屬分類 (對象關聯)
    private boolean del;      // 軟刪除標誌
    // getter/setter/toString 省略
}

二、持久層 (BookDao - 重點處理關聯查詢)

public class BookDao {
    private QueryRunner qr = new TxQueryRunner();

    // 查詢所有上架圖書
    public List findAll() {
        try { return qr.query("select * from book where del=false", new BeanListHandler<>(Book.class)); }
        catch (SQLException e) { throw new RuntimeException(e); }
    }

    // 按分類查詢
    public List findByCategory(String cid) {
        try { return qr.query("select * from book where cid=? and del=false", new BeanListHandler<>(Book.class), cid); }
        catch (SQLException e) { throw new RuntimeException(e); }
    }

    // 加載詳情 (關聯查詢分類信息)
    public Book findByBid(String bid) {
        try {
            String sql = "select b.*, c.cid as c_cid, c.cname as c_cname from book b left join category c on b.cid=c.cid where b.bid=?";
            Map map = qr.query(sql, new MapHandler(), bid);
            if (map == null) return null;
            Category category = CommonUtils.toBean(map, Category.class, "c_"); // 前綴映射
            Book book = CommonUtils.toBean(map, Book.class);
            book.setCategory(category);
            return book;
        } catch (SQLException e) { throw new RuntimeException(e); }
    }

    // 獲取分類下圖書總數 (分頁用)
    public int getCountByCid(String cid) {
        try {
            Number cnt = (Number) qr.query("select count(*) from book where cid=? and del=false", new ScalarHandler(), cid);
            return cnt.intValue();
        } catch (SQLException e) { throw new RuntimeException(e); }
    }

    // 添加圖書
    public void add(Book book) {
        try {
            qr.update("insert into book values(?,?,?,?,?,?)",
                book.getBid(), book.getBname(), book.getPrice(), book.getAuthor(), book.getImage(), book.getCategory().getCid());
        } catch (SQLException e) { throw new RuntimeException(e); }
    }

    // 軟刪除
    public void delete(String bid) {
        try { qr.update("update book set del=true where bid=?", bid); }
        catch (SQLException e) { throw new RuntimeException(e); }
    }

    // 修改圖書
    public void edit(Book book) {
        try {
            qr.update("update book set bname=?, price=?, author=?, image=?, cid=? where bid=?",
                book.getBname(), book.getPrice(), book.getAuthor(), book.getImage(), book.getCategory().getCid(), book.getBid());
        } catch (SQLException e) { throw new RuntimeException(e); }
    }
}

三、業務層 (BookService)

public class BookService {
    private BookDao bookDao = new BookDao();

    public List findAll() { return bookDao.findAll(); }
    public List findByCategory(String cid) { return bookDao.findByCategory(cid); }
    public Book load(String bid) { return bookDao.findByBid(bid); }
    public void add(Book book) { bookDao.add(book); }
    public void delete(String bid) { bookDao.delete(bid); }
    public void edit(Book book) { bookDao.edit(book); }
}

四、表現層 (BookServlet)

public class BookServlet extends BaseServlet {
    private BookService bookService = new BookService();

    // 查詢所有 -> list.jsp
    public String findAll(HttpServletRequest req, HttpServletResponse resp) {
        req.setAttribute("bookList", bookService.findAll());
        return "f:/jsps/book/list.jsp";
    }

    // 按分類查詢 -> list.jsp
    public String findByCategory(HttpServletRequest req, HttpServletResponse resp) {
        String cid = req.getParameter("cid");
        req.setAttribute("bookList", bookService.findByCategory(cid));
        return "f:/jsps/book/list.jsp";
    }

    // 加載詳情 -> desc.jsp
    public String load(HttpServletRequest req, HttpServletResponse resp) {
        req.setAttribute("book", bookService.load(req.getParameter("bid")));
        return "f:/jsps/book/desc.jsp";
    }
}

五、JSP 頁面關鍵片段

list.jsp - 圖書列表 (支持分頁、加入購物車)

<c:forEach items="${bookList}" var="book">
    <div class="book-item">
        <img src="${pageContext.request.contextPath}/${book.image}" alt="${book.bname}" />
        <h4>${book.bname}</h4>
        <p>作者:${book.author}</p>
        <p>價格:¥${book.price}</p>
        <a href="BookServlet?method=load&bid=${book.bid}">查看詳情</a>
        <button onclick="addToCart('${book.bid}')>加入購物車</button>
    </div>
</c:forEach>

desc.jsp - 詳情頁

<div class="book-detail">
    <img src="${pageContext.request.contextPath}/${book.image}" />
    <h2>${book.bname}</h2>
    <p>作者:${book.author}</p>
    <p>分類:${book.category.cname}</p>
    <p>價格:¥${book.price}</p>
    <p>${book.description}</p> <!-- 假設擴展描述字段 -->
    <button onclick="addToCart('${book.bid}')>加入購物車</button>
</div>

六、數據庫表

CREATE TABLE book (
    bid VARCHAR(32) PRIMARY KEY,
    bname VARCHAR(100) NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    author VARCHAR(50),
    image VARCHAR(200),
    cid VARCHAR(32),
    del BOOLEAN DEFAULT FALSE,
    FOREIGN KEY (cid) REFERENCES category(cid)
);

七、關鍵技術點總結

  • 關聯查詢映射:使用 MapHandler + CommonUtils.toBean(map, Class, prefix) 將聯表結果分離映射到兩個對象,再建立關聯。
  • 軟刪除:del 字段避免物理刪除導致關聯數據孤立,查詢統一加 del=false。
  • 圖片存儲:路徑存相對路徑 (如 book_img/xxx.jpg),實體文件存服務器磁盤或對象存儲 (OSS)。
  • 事務控制:TxQueryRunner 確保多表操作原子性 (如添加圖書同時更新分類統計)。

八、擴展建議

  • 全文搜索:集成 Elasticsearch/Lucene 實現書名、作者、ISBN 模糊搜索。
  • 圖書評分評論:新增 comment 表,關聯 bid、uid。
  • 推薦系統:基於協同過濾/內容推薦,記錄用戶瀏覽購買行為。
  • 庫存扣減:下單時樂觀鎖 (version 字段) 或分布式鎖扣減庫存。
  • 圖片上傳:集成 Spring MultipartFile + OSS SDK,生成縮略圖、水印。

圖書模塊是電商系統的商品中心,數據模型設計、查詢性能、擴展性直接決定業務上限,需持續優化。

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