1.el表达式简介
el全名为expression language。el的主要作用为:
1.1 获取数据
使用el表达式获取数据的语法:"${标识符}"
el表达式语句在执行时,会调用pagecontext.findattribute方法,用标识符为关键字,分别从page、request、session、application四个域中查找相应的对象,找到则返回相应对象,找不到则返回""(空字符串)。若没有指定哪个属性范围,它的默认值会从page范围找,假如找不到,再依序到request,session,application范围找。假如全部的范围都找不到时,就返回null值了。如下:${ }中没有sessionscope属性范围,依旧可以读到存储的数据。
<body>
<%
customer customer=new customer();
customer.setname("koala");
customer.setage(12);
session.setattribute("customer",customer);
%>
<br>
name: ${customer.name}
<br>
age: ${customer.age}
</body>
el表达式可以很轻松获取javabean的属性,或获取数组、collection、map类型集合的数据。
获取request域中的对象:
<body>
<% request.setattribute("name", "koala"); %>
name: ${name}
</body>
获取javabean的属性:
<body>
<%
customer customer=new customer();
customer.setage(21);
request.setattribute("customer",customer);
%>
customer's age: ${customer.age}
</body>
获取list集合中指定位置的元素:
<body>
<%
customer customer1=new customer();
customer1.setage(21);
customer customer2=new customer();
customer2.setage(23);
list<customer> list=new arraylist<customer>();
list.add(customer1);
list.add(customer2);
request.setattribute("list", list);
%>
customer2's age:${list[1].age}
</body>
1.2 执行运算
语法:${运算表达式},el表达式支持如下运算符:
1.2.1 关系运算符
1.2.2 逻辑运算符
1.2.3 empty运算符
检查对象是否为null(空)
1.2.4 二元表达式
${username==null?"":user.name}
1.2.5 []和.号运算符
el提供.和[]两种运算符来存取数据,两者所代表的意思是一样的。
如下,当域对象的属性名中有特殊字符“.”时使用[]会很方便:
<body>
<%
customer customer=new customer();
customer.setname("koala");
session.setattribute("com.d.dsa",customer);
%>
<br>
name: ${sessionscope["com.d.dsa"].name}
</body>
2.el的隐含对象
el中一共有11个隐含对象,可以将它分成三类:
2.1 与范围有关的隐含对象
<body>
time:${applicationscope.time}
<!-- 相当于
<%=application.getattribute("time") %>
-->
<%
application.setattribute("time",new date());
%>
</body>
2.2 与输入有关的隐含对象
el.jsp中:
<body>
<a href="http://localhost:8080/mywebproject/jsptest/el2.jsp?score=98&name=a&name=b">to el2 page</a>
</body>
el2.jsp中:
<body>
score:${param.score}
<!--相当于:
<%= request.getattribute("score")%>
-->
<br>
names:${paramvalues.name[0]} and ${paramvalues.name[1]}
</body>
运行el.jsp:
点击超链接:
注:
names:${paramvalues.name[0].class.name}
相当于
<%= request.getparametervalues("name")[0].getclass().getname()%>
也就是只要返回值有get...方法,就可以使用el方法调用。
2.3 其它请求对象
<context-param>
<param-name>initname</param-name>
<param-value>koala</param-value>
</context-param>
在jsp文件中使用initparam:${initparam.initname}即可获得当前web应用的初始化参数koala。
contextpath:${pagecontext.request.contextpath}
sessionid:${pagecontext.session.id}
sessionattributenames:${pagecontext.session.attributenames}
3.el的关系运算符
比较重要的是三目运算符:${param.score > 60 ? "及格" : "不及格"}
4.empty运算符
empty可以作用于一个集合,若集合不存在或集合中没有元素,其结果都为true。
<body>
<%
list<string> names=new arraylist<string>();
names.add("abc");
request.setattribute("names",names);
%>
names is empty:${empty requestscope.names}
</body>
运行jsp文件,
搜索微信公众号“程序员考拉”欢迎关注!
如对本文有疑问, 点击进行留言回复!!
before社区电量是什么意思 Before社区电量获得方法
RecycleView入门详解(教你全面掌握RecycleView用法)
动态权限请求框架RxPermissions(几行代码搞定权限)
URL路径@PathVariable出现点号“.“时值遭截断问题
网友评论