一.EL表达式介绍
- Expression Language表达式语言
- 目的:为了使JSP写起来更加简单。
- 表达式语言的灵感来自于 ECMAScript 和 XPath表达式语言,它提供了在 JSP 中简化表达式的方法。
- EL表达式的格式 ${表达式}
二.常用的表达式
1.运算符
a.算术运算符:+, -, *, /
${1+1 }<br>
${2-1 }<br>
${2*2 }<br>
${2/1 }<br>
${5%2 }<br>
b.比较运算符:> < >= <= ==
${1 > 2 }<br>
${2 >= 2 }<br>
${2 == 1 }<br>
注:输出值为true或者是false
c.逻辑运算符: &&(and) ||(or) !(not)
${true && true }<br>
${true and false}<br>
${true || false }<br>
${true or false}<br>
${!true }<br>
${not true}
d.空运算符:empty
用来判断字符串,数组,集合中的数据是否为null或者是否长度为0
<%
//String s = null;
//String s = "";
//String s = "hello";
//request.setAttribute("s", s);
ArrayList<String> al = new ArrayList<>();
al.add("aaa");
request.setAttribute("al", al);
%>
<%-- ${empty s}<br>
${not empty s} --%>
${empty al}
2.获取值
- EL只能从四大域中获取属性
- 如果想要EL表达式来获取数据,必须将数据存储到域中,我们通过EL表达式从域中获取数据
域名称:
request --> requestScope
session --> sessionScope
pageContext --> pageScope
application --> applicationScope
方法:
a. ${域名称.键名}
<%
String name = "jack";
//request.setAttribute("aaa", name);
//session.setAttribute("aaa", name);
//pageContext.setAttribute("aaa", name);
application.setAttribute("aaa", name);
%>
<%-- ${requestScope.aaa} --%>
<%-- ${sessionScope.aaa } --%>
<%-- ${pageScope.aaa} --%>
${applicationScope.aaa }
b.${键名}
注意:这种写法会自动的从域中查询键名,有就获取,没有就不获取,但是查找也分先后顺序, 从小到大查找
pageContext < request < session < application
<%
/* String name = "tom";
request.setAttribute("name", name); */
//pageContext.setAttribute("name", "tom");
//request.setAttribute("name", "jerry");
//session.setAttribute("name", "rose");
//application.setAttribute("name", "jack");
%>
<%-- ${requestScope.name} --%>
${name }
3.获取对象中的数据
a.获取普通类对象的数据
${键名.属性名}
<%
User user = new User();
user.setName("tom");
user.setAge(18);
request.setAttribute("user", user);
%>
${user }<br>
${user.name}<br>
${user.age }<br>
${user.aaa }
b.获取集合类对象的数据
1.单列集合
${键名[索引]}
<%
ArrayList al = new ArrayList();
al.add("aaa");
al.add("bbb");
al.add("ccc");
application.setAttribute("list", al);
%>
${list }<br>
${list[0] }<br>
${list[1] }<br>
${list[2] }<br>
2.双列集合
${域中的键名.集合中的键名}
${域中的键名['集合中的键名']}
<%
Map<String, String> map = new HashMap<>();
map.put("name", "tom");
map.put("age", "18");
application.setAttribute("map", map);
%>
${map }<br>
${map.name }<br>
${map.age }<br>
${map['name'] }<br>
${map['age'] }