EL(Expression Language)
表达语言是JSP2.0版本中引入的新特性,它用于JSP文件中的数据访问。这种表达式语言能简化JSP文件中数据访问的代码,可用来替代传统的基于<%=和%>形式的Java表达式,以及部分基于<%和 %>形式的Java程序片段。
基本语法
- EL表达式的基本形式为: {“符号开头,以”}"结尾。如果在JSP文件的模板文本中使用EL表达式,那么表达式的值会输出到网页上。
例如以下Java表达式和EL表达式的作用相同,都用于输出请求参数username:
Java表达式:<%=request.getParameter("username")%>
EL表达式:${param.username}
- EL表达式和Java表达式一样,既可以直接插入JSP文件的模板文本中,也可以作为JSP标签的属性的值,例如以下jsp:setProperty标签的value属性的值为EL表达式${myPageBean.count+1}:
<jsp:useBean id="myPageBean" scope="page" class="mypack.CounterBean"/>
<jsp:setProperty name="myPageBean" property="count" value="${myPageBean.count+1}">
Current count value is :${myPageBean.count}
- 访问对象的属性及数组的元素
EL表达式语言可以使用点号运算符“.”来访问对象的属性,例如表达式 {customer[“name”]}
EL运算符
- 算术运算符
- 例如: {‘a’+‘b’}则会出现异常。
- 关系运算符
>
或者 gt
, 例如:${8>9} 或者 ${8 gt 9 }
>=
或者ge
, 例如:${45>=9} 或者 ${45 ge 9 }
< 或者 lt, 例如:${4<9} 或者 ${4 lt 9 }
<= 或者 le, 例如:${9<=8} 或者 ${9 le 8 }
== 或者 eq, 例如:${4==4} 或者 ${4 eq 4 }
!= 或者 ne, 例如:${4!=3} 或者 ${4 ne 3 }
- 逻辑运算符
&& 或者 and, 例如:${false && false} 或者 ${false and false }
|| 或者 or, 例如:${true || false} 或者 ${true or false }
! 或者 not,例如: {false}) 或者 ${not true }
empty 检查是否为null.
- 三元运算符
a ? b:c
隐含对象
这11个隐含对象可以分为以下四种类型。
- 表示Http请求中的特定数据:包括head,headerValues,param,paramValues和cookie,举例:
${header["user-agent"]}
等价于<%=request.getHeader("user-agent")%>
${header.host}
等价于<%=request.getHeader("host")%>
${Cookie.username.value}
等价于:调用名为“username”的Cookie对象的getValue()方法
${param.username}
等价于<%=request.getParameter("username")%>
对于${header[“user-agent”]}由于user-agent存在“-”,所以不能采用“.”进行访问
- 表示特定的范围,包括PageScope,requestScope,sessionScope,和applicationScope,
${sessionScope,.cart.total}
等价于:调用会话范围内的名为"cart"的ShoppingCart对象的getTotal()方法
${applicationScope.counter.count}
等价于:调用Web应用范围内的属性名为“counter”的counterBean对象的getCount()方法
- 表示PageCounter对象
${pageContext.servletContext.serverInfo}
等价<%=application.getServerInfo()%>
${pageContext.request.requestURL}
等价于<%=request.getRequestURL()%>
${pageContext.response.characterEncoding}
等价于<%=response.getCharacterEncoding()%>
${pageContext.session.creationTime}
等价于<%=session.getCreationTime()%>
- 表示Web应用的初始化参数集合,为initParam
${initParam.driver}
等价于<%=application.getInitParameter("driver")%>
命名变量
EL表达式中的变量称为命名变量,它不是JSP文件中的局部变量或者实例变量,而是存放在特定范围内的属性,命名变量的名字与属性名字对应,例如${username}等价于以下代码:
<%
String username=(String)pageContext.findAttribute("username");
if(username!=null)
{
%>
<%=username%>
<%}%>
再例如:
${cart.total}
<% ShoppingCart cart=(ShoppingCart)pageContext.findAttribute("cart");
if(cart!=null){
%>
<%=cart.getTotal()%>
<%}%>
使用EL表达式的JSP
<tr>
<td>\${5+2}</td>
<tr>
"$“代表转义字符,代表真正的”$"字符
读取HTML表单数据
<form action="form.jsp" method="GET">
name=<input type="text" name="username" value="${param["username"]}">
<p>
The name is :${param:username}
<jsp:setProperty name="myPageBean" property="count" value="${myPageBean.count+1}">
<p>
current count value is : ${myPageBean.count}
current driver is :${applicationScope.driver}
定义和使用EL函数
配合tld文件使用