JSP 表达式语言

EL 的语法、隐式对象、运算符、空值处理与函数调用。

Intermediate
Key PointsEL 用 ${} 从四个作用域取值,自动处理 null;它不能写语句,只能写表达式。

基本语法

JSP
${user.name}
${user.address.city}
${users[0].name}
${map['key']}
${list.size()}
${1 + 2 * 3}
${empty user}

${user.name} calls getUser().getName(); a miss yields null printed as empty. . and [] mix freely, and [] accepts a variable: ${users[i].name}.

隐式对象

ObjectReturns
pageScopepage 作用域里的属性 Map
requestScoperequest 作用域属性
sessionScopesession 作用域属性
applicationScopeapplication 作用域属性
param请求参数(单值)
paramValues请求参数数组
header / headerValues请求头
cookieCookie Map
pageContextPageContext 本身
initParamcontext-param

运算符

JSP
${a + b}  ${a - b}  ${a * b}  ${a / b}  ${a % b}
${a == b}  ${a != b}  ${a < b}  ${a >= b}
${a and b}  ${a or b}  ${not a}
${empty list}  ${not empty list}
${a > 0 ? '正' : '非正'}
${user.name == 'Ada' ? 'is Ada' : 'not Ada'}

== compares values (string content, not identity), so ${name == 'Ada'} works. That differs from Java's == on String and is deliberate in EL.

空值处理

JSP
<%-- 以下四种情况 empty 都为 true --%>
${empty nullValue}      <%-- null --%>
${empty ""}             <%-- 空串 --%>
${empty emptyList}      <%-- 空集合 --%>
${empty emptyArray}     <%-- 空数组 --%>

<%-- 直接输出会显示空串,不会显示 null --%>
<p>${missing.name}</p>

<%-- 取默认值 --%>
${empty user.nickname ? user.name : user.nickname}

${missing.name} does not throw even though missing is null — EL short-circuits to empty. That keeps the page from 500ing on missing data, but also hides "forgot to set the attribute" bugs.

调用方法

JSP
${list.size()}
${map.containsKey('k')}
${str.toUpperCase()}
${user.getDisplayName()}

<%-- 需要 JSP 2.2+ / EL 2.2,且方法必须是 public --%>
EL has no if, for or assignment. Use <c:if> / <c:forEach> for control flow; nesting ternaries three deep inside ${} reads far worse than the JSTL equivalent.

关闭 EL

JSP
<%-- 整页关闭:页面上的 ${} 原样输出,适合演示模板语法 --%>
<%@ page isELIgnored="true" %>

<%-- 局部转义:输出字面量 ${} --%>
\${notEvaluated}

isELIgnored="true" is useful on pages that teach EL syntax, or when upgrading an old project where legacy ${} must not be evaluated.

Friends & Partners