1.EL表达式介绍
- EL(Expression Language):表达式语言,在 JSP 2.0 规范中加入的内容,也是 Servlet 规范的一部分。
- 作用:在 JSP页面中获取数据(请求中的数据或者域对象中的数据)。让我们的JSP脱离java代码块和JSP表达式
- 语法:使用EL表达式能够简化JSP页面中Java代码的编写。格式非常简单,只需要在JSP页面中嵌入
${表达式}
即可
2.用三种方式获取域对象中的数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>EL表达式快速入门</title>
</head>
<body>
<%--1.向域对象中添加数据--%>
<% request.setAttribute("username","zhangsan");%>
<%--2.获取数据--%>
java代码块<%out.println(request.getAttribute("username"));%><br/>
jsp表达式<%=request.getAttribute("username")%><br/>
EL表达式${username}
</body>
</html>
3.EL表达式获取不同类型数据
- 1.EL表达式没有空指针异常。
- 2.EL表达式没有索引越界。
- 3.EL表大式没有字符串的拼接。
字符串拼接[不同类型用+号拼接会做加法[出现数据格式化异常]]
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>EL表达式获取不同类型数据</title>
</head>
<body>
<%--1.获取基本数据类型 [页面域]--%>
<%pageContext.setAttribute("num",10);%>
基本数据类型:${num}<br/>
<%--2.获取自定义对象类型--%>
<%Student stu = new Student("zhangsan", 23);
pageContext.setAttribute("student",stu);
%>
自定义对象类型${student}<br/>
<%--3.获取数组类型--%>
<% String []arr={"hello","world"};
pageContext.setAttribute("array",arr);
%>
数组类型${array[0]}<br/>
<%--4.获取List集合--%>
<%
Student student1=new Student("张三",20);
Student student2=new Student("张益达",22);
ArrayList<Student> list=new ArrayList<>();
list.add(student1);
list.add(student2);
request.setAttribute("students",list);
%>
<!--需求1:使用EL表达式在页面展示student2的name和age值-->
${students[1].name}
<%--底层调用的getName,getAge方法--%>
${students[1].age}<br/>
----------------------------------------<br/>
<%--1.EL表达式没有空指针异常。--%>
<%--2.EL表达式没有索引越界:--%>
<%--3.EL表大式没有字符串的拼接。--%>
字符串拼接[不同类型用+号拼接会做加法[出现数据格式化异常]]
${students[1].name}${students[1].age}
----------------------------------------<br/>
<%--5.获取Map集合--%>
<%
HashMap<String,Student> map=new HashMap<>();
map.put("stu1",student1);
map.put("stu2",student2);
request.setAttribute("stuMap",map);
%>
<!--需求2:使用EL表达式在页面展示student3的name和age值-->
<%--${stuMap}--%>
${stuMap.stu1.name}
${stuMap.stu1.age}
</body>
</html>
4.EL表达式运算符
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>EL表达式运算符</title>
</head>
<body>
<%--empty 判断不为空为not empty
1.可以判断对象是否为空
2.可以判断字符串是否为空字符串
3.可以判断集合长度是否为0--%>
<%
String str1 =null;
String str2 ="123";
ArrayList list = new ArrayList();
pageContext.setAttribute("s1",str1);
pageContext.setAttribute("s2",str2);
pageContext.setAttribute("list",list);
%>
${empty s1}<br/>
${empty s2}<br/>
${empty list}<br/>
<%--三元运算符根据性别的数据来让性别单选框默认被选中--%>
<%pageContext.setAttribute("gender","women");%>
<input type="radio" value="男" name="gender" ${gender=="men"?"checked" :""}>男
<input type="radio" value="女" name="gender" ${gender=="women"?"checked" :""}>女
</body>
</html>
5.EL表达式获取项目虚拟路径
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>EL表达式获取项目虚拟路径</title>
</head>
<body>
<%=request.getContextPath()%>
${pageContext.request.contextPath}
</body>
</html>