Expression Language (EL) 以 ${...} 界定,支持 . 和 [] 兩種訪問操作符:
${user.userName} — 屬性訪問${user["userName"]} — 鍵訪問,支持特殊字符鍵名${list[0]} — 列表/數組索引訪問${map.key} / ${map["key"]} — Map 訪問| 分類 | 操作符 | 示例 | |
|---|---|---|---|
| 算術 | + - * / div % mod | ${price * quantity} | |
| 邏輯 | and or not | ${user.age > 18 and user.active} | |
| 關系 | == eq != ne < lt > gt <= le >= ge | ${score >= 60} | |
| empty | 判斷 null/空字符串/空集合/空數組 | ${!empty userList} | |
| 三元 | ? : | ${score >= 60 ? '及格' : '不及格'} |
| 對象 | 類型 | 用途 | 示例 |
|---|---|---|---|
| pageContext | PageContext | 訪問 ServletContext、Request、Response、Session 等 | ${pageContext.request.requestURI} |
| pageScope | Map | 頁面作用域屬性 | ${pageScope.attrName} |
| requestScope | Map | 請求作用域屬性 | ${requestScope.user.name} |
| sessionScope | Map | 會話作用域屬性 | ${sessionScope.loginUser} |
| applicationScope | Map | 應用作用域屬性 | ${applicationScope.config} |
| param | Map | 單值請求參數 | ${param.id} |
| paramValues | Map | 多值請求參數(數組) | ${paramValues.ids[0]} |
| header | Map | 單值請求頭 | ${header["User-Agent"]} |
| headerValues | Map | 多值請求頭 | ${headerValues["Accept-Language"]} |
| cookie | Map | Cookie 值 | ${cookie.JSESSIONID.value} |
| initParam | Map | 上下文初始化參數 | ${initParam.contextConfigLocation} |
無作用域前綴時(如 ${user}),按 page → request → session → application 順序調用 pageContext.findAttribute() 查找。建議始終顯式指定作用域(如 ${requestScope.user}),提升性能並避免歧義。
public class ElFunctions {
public static String formatDate(Date date, String pattern) {
return new SimpleDateFormat(pattern).format(date);
}
public static String upperCase(String str) {
return str == null ? "" : str.toUpperCase();
}
}
/WEB-INF/tlds/functions.tld)<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="https://java.sun.com/xml/ns/javaee"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>fn</short-name>
<uri>https://example.com/fn</uri>
<function>
<name>formatDate</name>
<function-class>com.example.ElFunctions</function-class>
<function-signature>java.lang.String formatDate(java.util.Date, java.lang.String)</function-signature>
</function>
<function>
<name>upperCase</name>
<function-class>com.example.ElFunctions</function-class>
<function-signature>java.lang.String upperCase(java.lang.String)</function-signature>
</function>
</taglib>
<%@ taglib prefix="fn" uri="https://example.com/fn" %>
<body>
當前時間:${fn:formatDate(new java.util.Date(), 'yyyy-MM-dd HH:mm:ss')}<br/>
大寫轉換:${fn:upperCase('hello world')}
</body>
<name> 為 EL 中調用的函數名,<function-signature> 必須精確匹配方法簽名(含包名)熟練掌握 EL 表達式,能大幅簡化 JSP 頁面代碼,實現視圖與邏輯的清晰分離。