SCWCD 1.4 (考試代碼 310-081) 較 1.3 (080) 新增 Expression Language (EL) 與 JSTL 兩大章節。本文整理官方考試大綱重點與核心語法,作為複習速查手冊。
EL 提供 11 個隱含物件,皆為 Map 型態,鍵值對應各作用域屬性或請求參數:
| 隱含物件 | 對應內容 |
|---|---|
| pageScope | PageContext 屬性 |
| requestScope | Request 屬性 |
| sessionScope | Session 屬性 |
| applicationScope | ServletContext 屬性 |
| param | 單一請求參數 (String) |
| paramValues | 多值請求參數 (String[]) |
| header | 單一請求標頭 |
| headerValues | 多值請求標頭 |
| cookie | Cookie 物件 Map |
| initParam | Context 參數 |
| pageContext | PageContext 物件本身 |
${pageScope.user.name} // 點運算子:屬性名為合法識別碼時
${sessionScope['user-name']} // 括號運算子:屬性名含特殊字元或動態鍵值
${paramValues.color[0]} // 存取陣列/List 元素
${header['User-Agent']} // 存取標頭
<%@ taglib prefix="c" uri="https://java.sun.com/jstl/core" %>
同時需在 web.xml 宣告 TLD:
<taglib>
<taglib-uri>https://java.sun.com/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/tld/core.tld</taglib-location>
</taglib>
| 分類 | 標籤 | 用途 |
|---|---|---|
| General Purpose | <c:out> | 輸出值,支援 XML 轉義,等同 ${...} 但更安全 |
| <c:catch> | 捕獲例外,將例外物件存入 var 變數,避免錯誤頁面機制啟動 | |
| Variables Support | <c:set> | 設定變數至指定作用域 |
| <c:remove> | 移除變數 | |
| Conditional | <c:if> | 單一條件判斷 |
| <c:choose> / <c:when> / <c:otherwise> | 多重條件分支 (類似 switch-case) | |
| Iterator | <c:forEach> | 遍歷 Collection、Map、陣列、整數範圍 |
| <c:forTokens> | 依分隔符號切割字串並遍歷 | |
| URL Related | <c:url> | 編碼 URL,自動加入 Session ID,支援參數嵌入 |
| <c:import> / <c:redirect> | 引入內容 / 重導向 |
You have <c:out value="${sessionScope.user.itemCount}" /> items.
<c:catch var="ex">
<c:import url="https://unstable-service/data"/>
</c:catch>
<c:if test="${ex != null}">
<p>Service unavailable: ${ex.message}</p>
</c:if>
<c:forEach var="item" items="${requestScope.products}" varStatus="status">
${status.count}. ${item.name} - ${item.price}
</c:forEach>
<c:url value="/shop/cart" var="cartUrl">
<c:param name="action" value="add"/>
<c:param name="id" value="${product.id}"/>
</c:url>
<a href="${cartUrl}">加入購物車</a>
var (變數名)、scope (作用域)、items (遍歷來源)、test (條件表達式)。<c:catch> 僅捕獲其主體內發生的例外,不會捕獲 JSP 頁面其他位置的錯誤。<c:import> 可跨 Context 引入資源,比 <jsp:include> 更強大。官方 JSTL 1.1 指南:https://java.boot.by/wcd-guide/ch09s03.html