在 JSP 中用 `
public class Category {
private Long id; // 主鍵
private String name;
// getter/setter
}
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<table>
<tr><th>名稱</th><th>操作</th></tr>
<c:forEach items="${categoryList}" var="category">
<tr>
<td><c:out value="${category.name}"/></td>
<td>
<!-- 方式一:超連結 GET(簡單、可收藏、不安全) -->
<a href="deleteCategory?id=${category.id}" onclick="return confirm('確定刪除?');">刪除</a>
<!-- 方式二:表單 POST(推薦、防 CSRF、支援大量資料) -->
<form action="deleteCategory" method="post" style="display:inline;" onsubmit="return confirm('確定刪除?');">
<input type="hidden" name="id" value="${category.id}"/>
<button type="submit">刪除</button>
</form>
<!-- 方式三:AJAX 非同步刪除(體驗佳、無刷新) -->
<button type="button" class="btn-delete" data-id="${category.id}">刪除</button>
</td>
</tr>
</c:forEach>
</table>
<script src="${pageContext.request.contextPath}/js/jquery-3.7.1.min.js"></script>
<script>
$(function() {
$('.btn-delete').click(function() {
if (!confirm('確定刪除?')) return;
var id = $(this).data('id');
var $row = $(this).closest('tr');
$.post('${pageContext.request.contextPath}/deleteCategory', {id: id}, function(resp) {
if (resp.success) $row.fadeOut(300, function() { $(this).remove(); });
else alert('刪除失敗:' + resp.msg);
}, 'json');
});
});
</script>
@WebServlet("/deleteCategory")
public class DeleteCategoryServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String idStr = req.getParameter("id");
if (idStr == null || idStr.isEmpty()) {
sendJson(resp, false, "缺少 ID"); return;
}
try {
long id = Long.parseLong(idStr);
categoryDao.deleteById(id); // 實際刪除邏輯
sendJson(resp, true, "刪除成功");
} catch (NumberFormatException e) {
sendJson(resp, false, "ID 格式錯誤");
} catch (Exception e) {
sendJson(resp, false, "伺服器錯誤:" + e.getMessage());
}
}
private void sendJson(HttpServletResponse resp, boolean success, String msg) throws IOException {
resp.setContentType("application/json;charset=UTF-8");
resp.getWriter().write(String.format("{\"success\":%b,\"msg\":\"%s\"}", success, msg));
}
}
| 方式 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 超連結 GET | 簡單、可書籤 | 不安全(CSRF)、瀏覽器歷史記錄殘留、長度限制 | 內部/低風險/唯讀資料 |
| 表單 POST | 標準、支援防 CSRF Token、無長度限制 | 頁面跳轉/重整 | 傳統應用、表單導向頁面 |
| AJAX POST | 無刷新、體驗好、可動畫 | 需 JS、需處理錯誤狀態 | 現代 SPA/後台管理系統 |
掌握「迴圈變數 `${category.id}` → URL 參數/隱藏欄位/data-* 屬性 → 後端 `request.getParameter("id")`」這條資料流,即可實現列表刪除功能。