本系列博客汇总在这里:EL 表达式和 JSTL 标签汇总
EL 内置对象
域隐藏对象
-
在 EL 表达式中,无需创建就可以使用的对象称之为 EL 隐藏(隐含、内置)对象。在 EL 中一共有 11 个隐藏对象,它们都与 Map 相似。其中 10 个是 Map,一个是 PageContext。
-
域隐藏对象
(1)使用 EL 表达式最为常用的就是获取域对象中保存的数据。例如:\${pageScope.xxx}
,表示获取在 pageContext 保存的数据。当然\${pageScope[‘xxx’]}
是相同的!
(2)pageScope:pageScope 是 Map<String,Object> 类型,${pageScope.xxx}
的功能相等与 pageContext.getAttribute(“xxx”)。两者的区别在于,前者在数据不存在时返回空字符串,而后者返回 null。
(3)requestScope:requestScope 是 Map<String, Object> 类型,装载了 request 对象中的所有数据;
(4)sessionScope:sessionScope 是 Map<String, Object> 类型,装载了 session 对象中的所有数据;
(5)applicationScope:applicationScope 是 Map<String, Object> 类型,装载了 application 对象中的所有数据;
(1)当 EL 中给出的不是隐藏对象时,表示在四个域中查找数据。例如:${a},表示
① 在 ${pageScope.a} 中查找,如果找到就返回;
② 在 ${requestScope} 中查找,如果找到就返回;
③ 在 ${sessionScope} 中查找,如果找到就返回;
④ 在 ${applicationScope} 中查找,如果找到就返回,找不到就返回空字符串。 -
示例
以上操作完整源码:<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="com.wyx.model.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% Person person = new Person(); person.setAge(21); person.setId(1); person.setName("weiyuxuan"); pageContext.setAttribute("person", person); //request.setAttribute("person", person); //session.setAttribute("person", person); //application.setAttribute("person", person); %> <% Person p = (Person)pageContext.getAttribute("person"); %> <%=p.getId()%> <%=p.getName()%> <%=p.getAge()%> <hr> <h1>EL表达式从page域中来取值</h1> <h2>${pageScope.person.id }</h2> <h2>${pageScope.person.name }</h2> <h2>${pageScope.person.age }</h2> <hr> <h1>EL表达式从request域中来取值</h1> <h2>${requestScope.person.id }</h2> <h2>${requestScope.person.name }</h2> <h2>${requestScope.person.age }</h2> <hr> <h1>EL表达式从session域中来取值</h1> <h2>${sessionScope.person.id }</h2> <h2>${sessionScope.person.name }</h2> <h2>${sessionScope.person.age }</h2> <hr> <h1>EL表达式从application域中来取值</h1> <h2>${applicationScope.person.id }</h2> <h2>${applicationScope.person.name }</h2> <h2>${applicationScope.person.age }</h2> <hr> <h1>EL表达式默认从域中来取值</h1> <h2>${person.id }</h2> <h2>${person.name }</h2> <h2>${person.age }</h2> </body> </html>
如有错误,欢迎指正!