【web后端(二十一)】jsp、servlet_EL表达式——scope范围中获取数据
2023-09-11 14:20:37 时间
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>
输出结果
相关文章
- Web测试的各个测试点,居然这么全!(文末送web测试方法大全一份)
- 若要使他人能够在远程计算机上查看此特定错误消息的详细信息,请在位于当前 Web 应用程序根目录下的“web.config”配置文件中创建一个 <customErrors> 标记。然后应将此 <cust
- jsp的4种作用域?
- 解决JSP中文乱码问题
- jsp页面用html引入vue.js注意问题
- 《Servlet、JSP和Spring MVC初学指南》——第1章 Servlets 1.1Servlet API概览
- 基于JSP实现(Web)企业公司管理系统【100010324】
- java中文乱码解决之道(七)—–JSP页面编码过程
- JSP Session管理
- JSP和Servlet中的几个编码的作用及原理
- 【IDEA】IDEA新建maven的web项目有pom.xml无Index.jsp
- java web中servlet、jsp、html 互相访问的路径问题
- 【web后端(十九)】jsp、servlet_内置标签——include
- 【web后端(十二)】jsp、servlet_servlet初始化参数、servelt上下文参数
- 【web后端(九)】jsp、servlet_会话管理_session
- 【web后端(四)】jsp、servlet_请求转发、请求派发
- 【web后端(三)】jsp、servlet_doPost_上传照片
- 【web后端(一)】jsp、servlet_查询字符串
- Jsp在Web.xml中的配置
- Grafana集成到自己的Web项目,通过搭建自己的实时数据监测与分析平台,把报表和图形展示集成到web项目进行整合开发,在网页上实现类似于Echarts的图形展示,构建领导驾驶舱大屏炫酷数据展示