EL表达式
EL表达式语言,用于简化JSP的输出;
EL表达式的基本语法:${表达式};
示例:
<h1>学生姓名:${student.name}</h1>
作用域对象
忽略书写作用域对象时,el则按作用域从小到大依次尝试获取(不建议忽略)
-
pageScope
:从当前页面取值 -
requestScope
:从当前请求中获取属性值 -
sessionScope
:从当前会话中获取属性值 -
applicationScope
:从当前应用获取全局属性值
EL表达式输出
- 语法:${[作用域.]属性名[.子属性]}
- EL表达式支持将运算结果进行输出
- EL支持绝大多数对象输出,本质是执行toString()方法
EL输出参数值
- EL表达式内置param对象来简化参数的输出
- 语法:
${param.参数名}
实例
Course.java
package el;
public class Course {
private int id;
private String name;
private String category;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Course() {
}
public Course(int id, String name, String category) {
super();
this.id = id;
this.name = name;
this.category = category;
}
@Override
public String toString() {
return "Course [id=" + id + ", name=" + name + ", category=" + category + "]";
}
}
El.java
package el;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class El
*/
@WebServlet("/el")
public class El extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public El() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Course course = new Course(1, "小明", "计算机");
request.setAttribute("course", course);
request.getRequestDispatcher("/el.jsp").forward(request, response);
}
}
el.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>
<b style="color: red;">${ requestScope.course }</b>
</body>
</html>
浏览器输入:http://localhost:8080/EL/el
页面显示:Course [id=1, name=小明, category=计算机]
el2.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>
<b style="color: red;">${ param.level }</b>
</body>
</html>
浏览器输入:http://localhost:8080/EL/el2.jsp?level=primary
页面显示:primary
网友评论