EL是JSP 2.0增加的技术规范,其全称是表达式语言(Expression Language)。EL语言是一种在页面中访问数据的语言,简洁,易于维护。
EL语法
在JSP中访问模型对象是通过EL表达式的语法来表达。所有EL表达式的格式都是以“${}”表示。
例如,${ userinfo}代表获取变量userinfo的值。
EL表达式访问,PageContext,Request,Session,Application中的对象
页面中有四个范围(scope),分别是pageScope页面范围,requestScope请求范围,sessionScope会话范围,applicationScope服务器范围
示例:先创建一个Servlet,在上述四个范围中存入数据,转发到index.jsp页面
DataServlet
package edu.xalead;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "DataServlet", urlPatterns = "/data")
public class DataServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//在request中存入数据
//在request中存入常量
request.setAttribute("a", "Hello");
request.setAttribute("b", 200);
request.setAttribute("c", true);
//在Session中存入常量
request.getSession().setAttribute("a", "World");
request.getSession().setAttribute("b", 220);
request.getSession().setAttribute("c", false);
//在ServletContext中存入常量
request.getServletContext().setAttribute("a", "!");
request.getServletContext().setAttribute("b", 222);
request.getServletContext().setAttribute("c", true);
//转发到index.jsp
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h3>获取request当中的常量</h3>
<h4>
<%--这两种形式表示都是一样的--%>
a : ${requestScope.a} <br/>
b : ${requestScope["b"]} <br/>
c : ${requestScope.c} <br/>
</h4>
<h3>获取session当中的常量</h3>
<h4>
a : ${sessionScope.a} <br/>
b : ${sessionScope.b} <br/>
c : ${sessionScope.c} <br/>
</h4>
<h3>获取servletContext当中的常量</h3>
<h4>
a : ${applicationScope.a} <br/>
b : ${applicationScope.b} <br/>
c : ${applicationScope.c} <br/>
</h4>
<h3>EL表达式访问范围的默认顺序:
page => request => session => application</h3>
<h4>
a : ${a} <br/>
b : ${b} <br/>
c : ${c} <br/>
</h4>
</body>
</html>
输出结果