JSTL 核心標籤庫 (uri="https://java.sun.com/jsp/jstl/core") 是 JSP 標準化開發的基石,提供 13 個標籤涵蓋表達式控制、流程控制、迭代、URL 操作四大類。本文系統整理各標籤語法、屬性、最佳實踐與 EL 整合要點。
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>`<c:out> - 安全輸出 (預設防 XSS)<c:out value="${user.name}" escapeXml="true" default="匿名用戶" />
<!-- 等價 body 寫法 -->
<c:out value="${user.name}" escapeXml="true">匿名用戶</c:out>
`escapeXml="true"` (預設) 轉義 `< > & " '` 等特殊字元。`default` 處理 `null` 值 (空字串不觸發)。
<c:set> - 設定範圍變數或 Bean 屬性<!-- 設定範圍變數 -->
<c:set var="siteName" value="MySite" scope="application" />
<c:set var="now" value="${new java.util.Date()}" />
<!-- 設定 Bean 屬性 (target 必須為 Map 或 JavaBean) -->
<c:set target="${user}" property="name" value="新名稱" />
<c:remove> - 移除範圍變數<c:remove var="tempVar" scope="session" />
<c:catch> - 捕獲異常避免頁面中斷<c:catch var="ex">
<% riskyOperation(); %>
</c:catch>
<c:if test="${ex != null}">發生錯誤: ${ex.message}</c:if>
<c:if> - 單一條件<c:if test="${user.loggedIn}">
歡迎, <c:out value="${user.name}"/>
</c:if>
<c:if test="${not empty param.msg}" var="hasMsg" scope="request" /> <!-- 無本體,存結果 -->
<c:choose>, <c:when>, <c:otherwise> - 多重互斥條件<c:choose>
<c:when test="${user.role == 'admin'}">管理員面板</c:when>
<c:when test="${user.role == 'editor'}">編輯器</c:when>
<c:otherwise>一般用戶</c:otherwise>
</c:choose>
<c:forEach> - 通用迭代 (Collection、Map、Array、Range、ResultSet)<!-- 範圍迭代 -->
<c:forEach var="i" begin="1" end="10" step="2">${i} </c:forEach>
<!-- 集合迭代 -->
<c:forEach var="item" items="${productList}" varStatus="status">
${status.index}: ${item.name} <c:if test="${status.last}">(最後一筆)</c:if>
</c:forEach>
<!-- Map 迭代 -->
<c:forEach var="entry" items="${paramValues}">
${entry.key} = ${entry.value}
</c:forEach>
`varStatus` 提供 `index` (0-based)、`count` (1-based)、`first`、`last`、`begin`、`end`、`step`。
<c:forTokens> - 字串分割迭代<c:forTokens var="token" items="a,b,c,d" delims=",">${token}</c:forTokens>
<c:import> - 包含遠端/本地資源 (支援 URL、檔案、FTP)<c:import url="https://example.com/header.html" var="header" scope="request" />
<c:import url="/WEB-INF/fragment.jsp">
<c:param name="title" value="動態標題" />
</c:import>
比 `
<c:url> - 重寫 URL (自動加 Session ID、Context Path、編碼參數)<c:url value="/product/detail" var="detailUrl">
<c:param name="id" value="${product.id}" />
<c:param name="ref" value="home" />
</c:url>
<a href="<c:out value='${detailUrl}'/>">詳情</a>
<c:redirect> - 客戶端重導向 (自動重寫 URL)<c:redirect url="/login">
<c:param name="error" value="session_expired" />
</c:redirect>
JSTL 核心標籤庫配合 EL 表達式,能將 JSP 頁面還原為純表現層模板,是邁向現代 Java Web 開發的必經之路。