為了對比 JSTL 的優勢,本篇使用傳統 JSP Scriptlet(<% ... %>)實現相同的留言列表分頁功能。雖然不推薦用於新專案,但理解其寫法有助於維護舊系統、排查問題。

<%@ page contentType="text/html;charset=UTF-8" import="java.util.*,com.example.model.*" %>
<html><head><title>留言列表 (Scriptlet)</title></head><body>
<h2>留言板 - 主題列表</h2>
<%
PageBean<Message> page = (PageBean<Message>) request.getAttribute("page");
List<Message> list = page.getList();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
%>
<table border="1" cellpadding="5" cellspacing="0" width="100%">
<tr style="background:#f0f0f0">
<th>標題</th><th>作者</th><th>發文時間</th><th>回覆數</th><th>操作</th>
</tr>
<% for (Message msg : list) { %>
<tr>
<td><%= msg.getTitle() %></td>
<td><%= msg.getUser().getUsername() %></td>
<td><%= sdf.format(msg.getPostTime()) %></td>
<td><%= msg.getReplyCount() %></td>
<td>
<a href="detail?id=<%= msg.getId() %>">詳情</a> |
<a href="replyForm?parentId=<%= msg.getId() %>">回覆</a> |
<a href="delete?id=<%= msg.getId() %>" onclick="return confirm('確定刪除?')">刪除</a>
</td>
</tr>
<% } %>
</table>
<!-- 分頁導航 -->
<div style="text-align:center; margin-top:10px">
<%
int currentPage = page.getCurrentPage();
int totalPage = page.getTotalPage();
String ctx = request.getContextPath();
%>
<a href="<%= ctx %>/list?pageNo=1">首頁</a>
<% if (currentPage > 1) { %>
<a href="<%= ctx %>/list?pageNo=<%= currentPage-1 %>">上一頁</a>
<% } %>
<% for (int i = 1; i <= totalPage; i++) { %>
<% if (i == currentPage) { %> [<%= i %>] <% } else { %>
<a href="<%= ctx %>/list?pageNo=<%= i %>"><%= i %></a>
<% } %>
<% } %>
<% if (currentPage < totalPage) { %>
<a href="<%= ctx %>/list?pageNo=<%= currentPage+1 %>">下一頁</a>
<% } %>
<a href="<%= ctx %>/list?pageNo=<%= totalPage %>">尾頁</a>
</div>
</body></html>
StringEscapeUtils.escapeHtml() 防 XSS,易遺漏。SimpleDateFormat 非線程安全,若宣告在類層級會有併發問題。request.getContextPath() 到處重複,維護成本高。| 維度 | JSTL 版 | Scriptlet 版 |
|---|---|---|
| 可讀性 | ⭐⭐⭐⭐⭐ | ⭐⭐ |
| 安全性 | 自動轉義 | 手動轉義 |
| 維護性 | 前後端分離 | 強耦合 |
| 效能 | 標簽編譯優化 | 即時編譯 |
| 學習曲線 | 需學標簽庫 | 純 Java 易上手 |
結論:新專案務必使用 JSTL(或 Thymeleaf、FreeMarker 等現代模板引擎);僅在維護十年以上遺留系統時接觸 Scriptlet。