分類模塊負責圖書分類的增刪改查,為前台導航菜單、後台管理提供數據支持。採用相同分層架構:Domain → DAO → Service → Servlet。
public class Category {
private String cid; // 分類 ID (UUID)
private String cname; // 分類名稱
// getter/setter/toString 省略
}
public class CategoryDao {
private QueryRunner qr = new TxQueryRunner();
// 查詢所有分類
public List findAll() {
try { return qr.query("select * from category", new BeanListHandler<>(Category.class)); }
catch (SQLException e) { throw new RuntimeException(e); }
}
// 按 ID 查詢
public Category findByCid(String cid) {
try { return qr.query("select * from category where cid=?", new BeanHandler<>(Category.class), cid); }
catch (SQLException e) { throw new RuntimeException(e); }
}
// 添加分類
public void add(Category category) {
try { qr.update("insert into category values(?,?)", category.getCid(), category.getCname()); }
catch (SQLException e) { throw new RuntimeException(e); }
}
// 修改分類
public void edit(Category category) {
try { qr.update("update category set cname=? where cid=?", category.getCname(), category.getCid()); }
catch (SQLException e) { throw new RuntimeException(e); }
}
// 刪除分類 (需先檢查是否有關聯圖書)
public void delete(String cid) {
try { qr.update("delete from category where cid=?", cid); }
catch (SQLException e) { throw new RuntimeException(e); }
}
}
public class CategoryService {
private CategoryDao categoryDao = new CategoryDao();
public List findAll() { return categoryDao.findAll(); }
public Category findByCid(String cid) { return categoryDao.findByCid(cid); }
public void add(Category category) { categoryDao.add(category); }
public void edit(Category category) { categoryDao.edit(category); }
public void delete(String cid) { categoryDao.delete(cid); }
}
public class CategoryServlet extends BaseServlet {
private CategoryService categoryService = new CategoryService();
// 查詢所有分類 -> left.jsp (左側導航)
public String findAll(HttpServletRequest req, HttpServletResponse resp) {
req.setAttribute("categoryList", categoryService.findAll());
return "f:/jsps/left.jsp";
}
// 後台管理:添加、修改、刪除、查詢單個 (略)
}
使用 JSTL 迭代渲染分類導航,點擊分類跳轉到圖書列表頁並攜帶 cid 參數。
<div class="category-nav">
<h3>圖書分類</h3>
<ul>
<c:forEach items="${categoryList}" var="cat">
<li><a href="<c:url value='/BookServlet'>?method=findByCategory&cid=${cat.cid}">${cat.cname}</a></li>
</c:forEach>
</ul>
</div>
CREATE TABLE category (
cid VARCHAR(32) PRIMARY KEY,
cname VARCHAR(20) UNIQUE NOT NULL
);
<frameset cols="200,*">
<frame src="CategoryServlet?method=findAll" name="leftFrame" />
<frame src="BookServlet?method=findAll" name="mainFrame" />
</frameset>
或現代單頁佈局:AJAX 載入分類,動態渲染側邊欄。
parent_cid 字段,遞歸查詢樹狀結構。findAll 結果。deleted 標誌位,避免誤刪數據丟失。分類模塊雖簡單,但作為導航入口,數據準確性與加載速度直接影響用戶體驗,務必做好緩存與索引。