概要
作用:将逻辑(java)和页面代码分离,简化代码,用于在页面输出内容。
- 从域对象找数据
- 使用内置对象
- 执行运算
怎么写:
${el表达式}
域对象
(1)jsp默认支持四个域对象:
HttpServletContext application; 整个项目
HttpSession session; 一次会话
HttpServletRequest requst ; 一次请求
HttpPageContext pageContext; 当前页面
(2)常用方法
setAttribute(键,值);
getAttribute(键);
removeAttribute(键);
(3)存取案例
从四大域存取对象
<%--四大域中存数据--%>
<%
application.setAttribute("name1", "baoqiang1");
session.setAttribute("name1", "baoqiang2");
request.setAttribute("name1", "baoqiang3");
pageContext.setAttribute("name1", "baoqiang4");
%>
<%--方式1:从四大域中取数据--%>
<%--这种方式,如果找不到对应的键,返回null--%>
<%=application.getAttribute("name1")%>
<%=session.getAttribute("name2")%>
<%=request.getAttribute("name3")%>
<%=pageContext.getAttribute("name4")%>
<%--方式2:从四大域中取数据(EL表达式)--%>
<hr/>
<%--这种方式,如果找不到对应的键,返回空串--%>
${applicationScope.name1}
${sessionScope.name2}
${requestScope.name3}
${pageScope.name4}
<hr/>
<%--方式3:从四大域中取数据(EL表达式)--%>
<%--这种方式,如果找不到对应的键,返回空串--%>
<%--这种方式,会从作用范围最小的域开始找,所以每个域的键的名字不能重复--%>
${name1}
${name2}
${name3}
${name4}
方式三查找顺序从小到大: pageContext-》requst-》session-》application
取对象属性
准备:
-
定义两个bean
public class Birthday { private int y; private int m; private int d; .....
public class Person { private Birthday birthday; private int age; .....
-
bean导入
<%@ page import="jsu.lcw.bean.Person" %> <%@ page import="jsu.lcw.bean.Birthday" %>
代码:
<%
request.setAttribute("person1",new Person(new Birthday(2020,1,1),2));
%>
${person1.birthday.y}
${person1.birthday.m}
${person1.birthday.d}
${person1.age}
取集合数据
导入类
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
-
List
<%--向域中存储List集合对象--%> <% ArrayList<Person> list = new ArrayList<Person>(); list.add(new Person(new Birthday(2020,1,1),1)); list.add(new Person(new Birthday(2020,1,1),2)); list.add(new Person(new Birthday(2020,1,1),3)); request.setAttribute("list", list); %> <%--使用El来获取域中的数据--%> <%=((ArrayList<Person>)request.getAttribute("key")).get(0).getAge()%> ${requestScope.list[0].name} ${list[0].name} ${list[0].birthday.year}
-
Map
<% Map<String, Person> map= new HashMap<String, Person>(); map.put("u1", new Person(new Birthday(2020,1,1),1)); map.put("u2", new Person(new Birthday(2020,1,1),1)); map.put("u3", new Person(new Birthday(2020,1,1),1)); request.setAttribute("map", map); %> <%--使用El来获取域中的数据--%> <%=(( Map<String, Person>)request.getAttribute("map")).get("u1").getAge()%> ${requestScope.map.u1.name} ${map.u1.name} ${map.u3.birthday.month}
运算符
语法
-
${java运算表达式子}
算数运算:${1+1}
比较运算:${1>2}
逻辑运算等:${2 and 3}
-
${empty 集合/对象} 判断集合或对象是否为空
其他应用:
- 在jsp页面上获得web应用的名称:
${pageContext.request.contextPath}
- 动态获取项目访问路径,如果项目访问路径修改了,那么不会影响页面或者Servlet内的地址修改
问题
如果el表达式编写正确的话,还没有执行,那么可以打开页面的el表达式功能,因为它默认是关闭的
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>