1.1 概念
EL使JSP写起来更简单、简洁。主要用于获取作用域中的数据
1.2 作用
用于替换作用域对象.getAttribute("name");
1.3 EL的应用(获取基本类型、字符串)
${scope.name} 获取具体某个作用域中的数据
${name} 获取作用域中的数据,逐级查找(pageContext、request、session、application)
1.3.1 EL应用案例
<%
//存储在request作用域
request.setAttribute("name","tom");
request.setAttribute("age",18);
%>
${requestScope.name} <%--获取request作用域中name对应的值,找到就返回,没找到返回"" --%>
${name}<%--从最小作用域逐级查找name对应的值,找到就返回,没找到返回"" --%>
1.3.2 EL和JSP脚本的区别
<%=request.getAttribute() %> 没有找到返回null
${requestScope.name} 没找到返回""
1.4 EL的应用(获取引用类型)
使用EL获取作用域中的对象调用属性时,只能访问对象的get方法,必须遵守命名规范定义
<%
Emp e = new Emp();
e.setName("gavin");
e.setAge(19);
request.setAttribute("e",e);
%>
${requestScope.e.name}<%-- 调用getName()方法 --%>
1.5 EL的应用(获取数组、集合的元素)
EL可以获取Array、List、Map中的元素,Set由于没下标,无法直接访问元素,后续可遍历
<%
int[] array = new int[]{1,2,3,4,5};
request.setAttribute("array",array);
List<Emp> emps = new ArrayList<>();
emps.add(new Emp(1,"gavin",2000,19));
emps.add(new Emp(2,"marry",3000,29));
emps.add(new Emp(3,"jack",4000,39));
request.setAttribute("emps",emps);
Map<String,String> maps = new HashMap<>();
maps.put("CN","中国");
maps.put("FK","法国");
maps.put("US","美国");
request.setAttribute("maps",maps);
%>
${requestScope.array[0]}
${requestScope.emps[0]} <%-- 也可以用 ${requestScope.emps.get(0)} --%>
${requestScope.maps.CN} <%-- 也可以用 ${requestScope.maps["US"]} -->
1.6 EL的运算符
操作符 | 描述 |
---|---|
. | 访问一个Bean属性或者一个映射条目 |
[] | 访问一个数组或者链表的元素 |
+ | 加 |
- | 减或负 |
* | 乘 |
/ or div | 除 |
% or mod | 取模 |
== or eq | 测试是否相等 |
!= or ne | 测试是否不等 |
< or lt | 测试是否小于 |
> or gt | 测试是否大于 |
<= or le | 测试是否小于等于 |
>= or ge | 测试是否大于等于 |
&& or and | 测试逻辑与 |
|| or or | 测试逻辑或 |
! or not | 测试取反 |
empty | 测试是否空值 |
1.6.1 EL表达式执行运算
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>运算符</title>
</head>
<body>
<%
request.setAttribute("num",1234);
%>
<h1>算术运算</h1>
${num + 1}<br/>
${num - 1}<br/>
${num * 2}<br/>
<h1>关系运算</h1>
${num == 1234}<br/>
${num != 1234}<br/>
${num > 1200}<br/>
${num < 1200}<br/>
...
</body>
</html>
1.6.2 empty关键字
<%
String s1="";
pageContext.setAttribute("s1", s1);
List list1 =new ArrayList();
pageContext.setAttribute("list1", list1);
%>
<!-- empty关键只要内容是空true -->
${empty s1}<br>
${empty list1}<br>
1.7 隐式对象
EL 表达式语言定义了11个隐式对象
隐含对象 | 描述 |
---|---|
pageScope | page 作用域 |
requestScope | request 作用域 |
sessionScope | session 作用域 |
applicationScope | application 作用域 |
param | Request 对象的参数,字符串 |
paramValues | Request对象的参数,字符串集合 |
header | HTTP 信息头,字符串 |
headerValues | HTTP 信息头,字符串集合 |
initParam | 上下文初始化参数 |
cookie | Cookie值 |
pageContext | 当前页面的pageContext |
1.7.1 获得应用上下文
<%=request.getContextPath() %>
${pageContext.request.contextPath}
1.7.2 获取Cookie对象
${cookie.username}//获取名为username的cookie对象
${cookie.password}//获取名为password的cookie对象
${cookie.password.value}//获取password的cookie的value值