Expression Language (EL) 旨在簡化 JSP 中的資料存取,語法為 ${expression}。它自動處理 null 值(不拋 NPE)、支援屬性導航(user.address.city)、集合索引(list[0])、Map 鍵值(map['key']),並提供豐富運算子,是現代 JSP 開發的基石。
| 類別 | 運算子 | 說明 |
|---|---|---|
| 存取 | . [] | 屬性存取 user.name、索引/鍵存取 list[0] map['key'] |
| 算術 | + - * / (div) % (mod) | ${price * quantity},自動型別轉換,除零返回 Infinity |
| 關係 | == (eq) != (ne) < (lt) > (gt) <= (le) >= (ge) | 字串比較按 Unicode 編碼,建議使用文字版(eq)提升可讀性 |
| 邏輯 | && (and) || (or) ! (not) | ${not empty list and list.size() > 0} |
| 條件 | ? : | ${user.vip ? 'VIP' : '普通'} |
| 空值 | empty | 判斷 null、空字串、空集合、空 Map、空陣列,${empty param.id} |
EL 按優先順序搜尋四大作用域:pageScope → requestScope → sessionScope → applicationScope。若變數名稱衝突,優先返回較小作用域的值。可顯式指定作用域避免歧義:
${pageScope.username} <%-- 僅搜尋 pageContext --%>
${requestScope.username} <%-- 僅搜尋 request --%>
${sessionScope.username} <%-- 僅搜尋 session --%>
${applicationScope.username}<%-- 僅搜尋 application --%>
${param.id}、${paramValues.hobby[0]})${cookie.JSESSIONID.value})<context-param> 初始化參數${pageContext.request.contextPath}、${pageContext.session.id}<c:if test="${empty user.nickname}">預設暱稱</c:if>
<c:if test="${not empty user.nickname}">${user.nickname}</c:if>
empty 關鍵字涵蓋所有「空」語義,比 == null 或 == '' 更安全。
${user.address?.city} <!-- EL 3.0 安全導航,address 為 null 返回 null 而非拋異常 -->
${user.address.city} <!-- EL 2.2 會拋 PropertyNotFoundException -->
若專案仍在 EL 2.2,可用 ${not empty user.address and not empty user.address.city} 規避。
<%@ taglib prefix="fn" uri="https://java.sun.com/jsp/jstl/functions" %>
<!-- 字串長度/截取/替換 -->
${fn:length(paramValues)} <%-- 多值參數個數 --%>
${fn:toLowerCase(param.keyword)} <%-- 大小寫轉換 --%>
${fn:substring(content, 0, 100)}... <%-- 摘要截取 --%>
${fn:replace(desc, '敏感詞', '***')} <%-- 內容過濾 --%>
${fn:split(tags, ',')} <%-- 字串轉陣列,配合 c:forEach 迭代 --%>
<%
Person p = new Person();
p.setName("王小明");
p.setAge(22);
request.setAttribute("p", p);
%>
姓名:${p.name} <!-- 自動呼叫 getName() -->
年齡:${p.age} <!-- 自動呼叫 getAge() -->
<!-- 巢狀物件 -->
地址:${p.address.city}
EL 遵循 JavaBean 規範,自動將 ${p.name} 映射為 p.getName(),布林屬性 isActive 映射為 isActive() 或 getActive()。
EL 表達式以簡潔語法、自動 null 安全、豐富隱含物件與運算子,成為 JSP 視圖層的核心表達工具。掌握 empty 判斷、四大作用域精準定位、param/cookie/header 參數存取、JavaBean 屬性導航,並善用 fn: 函數庫處理字串,即可編寫乾淨、健壯的視圖模板。建議升級至 Servlet 3.0+ 容器(Tomcat 7+),享受 EL 3.0 的 Lambda、Stream、安全導航等現代特性。