萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP EL 表達式語言完全手冊:語法、運算符、內置對象與自定義函數

EL (Expression Language) 簡介

EL 旨在簡化 JSP 頁面的數據訪問與邏輯判斷,替代繁瑣的 Scriptlet。語法結構:${expression}。JSP 2.0 起內置支持,無需額外配置。

一、EL 關鍵字與運算符對照表

EL 關鍵字對應 Java 運算符說明
div/除法
mod%取餘
eq==等於
ne!=不等於
lt<小於
gt>大於
le<=小於等於
ge>=大於等於
and&&邏輯與
or||邏輯或
not!邏輯非
true / falsetrue / false布爾字面量
nullnull空值
instanceofinstanceof類型判斷
empty-空值檢測(null、空串、空集合、空 Map、長度為 0 的數組)

二、EL 運算符優先級(高→低)

[]  .
()  
- (一元)  !  empty
*  /  div  %  mod
+  - (二元)
<  >  <=  >=  lt  gt  le  ge
==  !=  eq  ne
&&  and
||  or
? : (三元運算符 ${A ? B : C})

三、十一大隱含對象詳解

EL 隱含對象均為 java.util.Map 類型,鍵為屬性名/參數名,值為對應對象:

隱含對象作用域/來源等價 API典型用法
pageContextPageContextpageContext${pageContext.request.contextPath}
pageScopePagepageContext.getAttribute(name, PAGE_SCOPE)${pageScope.var}
requestScopeRequestrequest.getAttribute(name)${requestScope.user}
sessionScopeSessionsession.getAttribute(name)${sessionScope.cart}
applicationScopeApplicationapplication.getAttribute(name)${applicationScope.config}
param單值請求參數request.getParameter(name)${param.id}
paramValues多值請求參數request.getParameterValues(name)${paramValues.ids[0]}
header單值請求頭request.getHeader(name)${header['User-Agent']}
headerValues多值請求頭request.getHeaders(name)${headerValues.Accept}
cookieCookie 對象request.getCookies()${cookie.JSESSIONID.value}
initParam上下文初始化參數application.getInitParameter(name)${initParam.dbUrl}

訪問規則

  • ${username}:依次搜索 page → request → session → application,找到即返回,否則返回空串(不拋異常)
  • ${requestScope.username}:強制指定作用域,避免歧義
  • 屬性訪問:${user.name} 等價 ${user["name"]},後者支持特殊字符鍵名(如 ${user["my-name"]})
  • 集合訪問:${list[0]}、${map.key}、${map["key.with.dot"]}

四、自定義 EL 函數開發步驟

1. 編寫靜態方法類

package com.example.el;
public class StringFunctions {
    public static String toUpper(String value) {
        return value == null ? "" : value.toUpperCase();
    }
    
    public static String substring(String str, int begin, int end) {
        return str.substring(begin, end);
    }
}

2. 定義 TLD 文件 /WEB-INF/tlds/functions.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="https://java.sun.com/xml/ns/javaee"
        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="https://java.sun.com/xml/ns/javaee web-jsptaglibrary_2_1.xsd"
        version="2.1">
    <tlib-version>1.0</tlib-version>
    <short-name>myfn</short-name>
    <uri>https://example.com/functions</uri>
    
    <function>
        <name>toUpper</name>
        <function-class>com.example.el.StringFunctions</function-class>
        <function-signature>java.lang.String toUpper(java.lang.String)</function-signature>
    </function>
    
    <function>
        <name>substring</name>
        <function-class>com.example.el.StringFunctions</function-class>
        <function-signature>java.lang.String substring(java.lang.String, int, int)</function-signature>
    </function>
</taglib>

3. JSP 頁面引入並使用

<%@ taglib prefix="fn" uri="https://example.com/functions" %>
<!-- 或直接引用 TLD 路徑:uri="/WEB-INF/tlds/functions.tld" -->

${fn:toUpper("hello world")}       <!-- 輸出: HELLO WORLD -->
${fn:substring("abcdef", 1, 4)}    <!-- 輸出: bcd -->

五、實戰技巧與避坑指南

  • 禁用 EL:<%@ page isELIgnored="true" %> 或 web.xml 中 <el-ignored>true</el-ignored>
  • 空值安全:EL 自動處理 null,${user.address.city} 若中間任一環為 null,輸出空串而非拋 NPE
  • 類型轉換:EL 自動執行字符串→數字、字符串→布爾等轉換,${"10" + 5} 結果為 15
  • 日期格式化:EL 無內置格式化,配合 JSTL <fmt:formatDate> 或自定義函數
  • XSS 防護:EL 輸出不自動轉義,需配合 fn:escapeXml() 或 JSTL <c:out>
copyright © 萬盛學電腦網 all rights reserved