El表达式
EL(Expression Language)表达式语言,用于简化JSP的输出
EL表达式的基本语法:${表达式}
示例:<h1>学生姓名:${student.name}</h1>
在绝大多数场景下都是为了替换原有的out.print()语句,比原有的JSP输出提高了可读性
例子:
el.Student.java
package el;
public class Student {
private String name;
private String mobile;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
el.StudentServlet.java
@WebServlet("/info")
//...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Student stu = new Student();
stu.setName("韩信");
stu.setMobile(null);
String grade = "A";
request.setAttribute("student", stu);
request.setAttribute("grade", grade);
request.getRequestDispatcher("/info.jsp").forward(request, response); //请求转发
}
info.jsp
out.plint()方法输出内容
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="el.Student" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<%
Student stu = (Student)request.getAttribute("student");
out.println("<h1>"+stu.getName()+"</h1>");
%>
</body>
</html>
el表达式方式,不用考虑导入和字符串拼接的问题,一切都像html的书写方式,在原有的输出数据的地方也不需要增加jsp代码块
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>姓名:${requestScope.student.name }</h1>
<h2>手机:${requestScope.student.mobile }</h2>
<h2>等级:${requestScope.grade }</h2>
</body>
</html>
EL表达式的作用域对象
- El表达式内置四种作用域对象
- 忽略书写作用域对象时,EL则按作用域从小到大依次尝试获取
作用域对象 | 描述 |
---|---|
pageScope | 从当前页面取值 |
requestScope | 从当前请求中获取属性值 |
sessionScope | 从当前会话中获取属性值 |
applicationScope | 从当前应用获取全局属性值 |
尝试将request中的属性存储到session中,之前的信息则获取不到了,将infoi.jsp只作用域对象requestScope改成sessionScope或者忽略便可获取到数据
el.StudentServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Student stu = new Student();
stu.setName("韩信");
stu.setMobile(null);
String grade = "A";
//设置全局属性
request.getServletContext().setAttribute("grade", "C");
//设置session
HttpSession session = request.getSession();
session.setAttribute("student", stu);
session.setAttribute("grade", grade);
// request.setAttribute("student", stu);
// request.setAttribute("grade", grade);
request.getRequestDispatcher("/info.jsp").forward(request, response); //请求转发
}
EL表达式输出
语法:${[作用域.]属性名[.子属性]}
El表达式支持将运算结果进行输出
${emp.salary+1000}
${1<=3&&2>4}
EL支持绝大多对象输出,本质是执行toString()方法
EL输出参数值
El表达式内置param对象来简化参数的输出
语法:${param.参数名}
el.jsp
<h2>讲师:${param.teacher }</h2>
网址加参数:localhost:8080/el/info?teacher=老头