開發者需實作「從 MySQL 讀取資料顯示於 JSP 表格,每列含 Checkbox 供審核勾選,提交時將勾選值批次更新資料庫」。本文提供完整架構設計、代碼範例與關鍵技術點解析。
CREATE TABLE items (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
status TINYINT DEFAULT 0 COMMENT '0:待審核 1:通過 2:拒絕',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
| 環節 | 關鍵代碼 | 說明 |
|---|---|---|
| JSP 顯示 | <input type="checkbox" name="ids" value="<%=item.getId()%>"> | value 必須綁定資料庫主鍵 ID |
| Servlet 獲取 | String[] ids = request.getParameterValues("ids"); | 必須用 getParameterValues 獲取陣列,單值用 getParameter 只會取第一個 |
| 批次更新 | UPDATE items SET status=1 WHERE id IN (?,?,...) | 使用 PreparedStatement 批次處理或 IN 查詢,防止 SQL 注入 |
public class Item {
private int id;
private String name;
private int status; // 0待審 1通過 2拒絕
// getter/setter/toString
}
public class ItemDAO {
// 查詢所有
public List- findAll() { /* JDBC 查詢 */ }
// 批次審核通過
public int batchApprove(String[] ids) throws SQLException {
if (ids == null || ids.length == 0) return 0;
String placeholders = String.join(",", Collections.nCopies(ids.length, "?"));
String sql = "UPDATE items SET status=1 WHERE id IN (" + placeholders + ")";
try (Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
for (int i = 0; i < ids.length; i++) {
ps.setInt(i + 1, Integer.parseInt(ids[i]));
}
return ps.executeUpdate();
}
}
}
@WebServlet("/item/*")
public class ItemServlet extends HttpServlet {
private ItemDAO dao = new ItemDAO();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String action = req.getPathInfo(); // /list, /approve
if ("/list".equals(action)) {
req.setAttribute("items", dao.findAll());
req.getRequestDispatcher("/WEB-INF/views/item_list.jsp").forward(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String[] ids = req.getParameterValues("ids");
int count = dao.batchApprove(ids);
req.setAttribute("message", "成功審核 " + count + " 筆資料");
doGet(req, resp); // 重導向列表頁
}
}
<form method="post" action="<%=request.getContextPath()%>/item/approve">
<table class="table">
<thead>
<tr><th>選取</th><th>ID</th><th>名稱</th><th>狀態</th></tr>
</thead>
<tbody>
<c:forEach items="${items}" var="item">
<tr>
<td><input type="checkbox" name="ids" value="${item.id}"
${item.status == 1 ? 'disabled checked' : ''}></td>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.status == 0 ? '待審核' : (item.status == 1 ? '已通過' : '已拒絕')}</td>
</tr>
</c:forEach>
</tbody>
</table>
<button type="submit" class="btn btn-primary">批次審核通過</button>
</form>
$('[name="ids"]').prop('checked', this.checked)| 錯誤 | 後果 | 修正 |
|---|---|---|
Checkbox 無 value 屬性 | 提交空字串,無法識別 ID | 必須 value="${item.id}" |
用 getParameter("ids") | 只取到第一個勾選值 | 必須 getParameterValues("ids") |
| 直接拼接 SQL | SQL 注入風險 | 使用 PreparedStatement 佔位符 |
| 未檢查 ids 為 null | 無勾選時拋 NPE | 判空後再處理 |
Checkbox 批次操作核心在於:JSP 綁定 ID 到 value、Servlet 用 getParameterValues 獲取陣列、DAO 批次 SQL 更新。掌握這三步,配合 JSTL/EL 表達式簡化視圖,即可實作穩健的審核功能。