jsp四大内置域数据对象的范围测试

本文通过实例展示了JSP中pageContext、request、session和application四大域对象的作用范围和生命周期。在没有请求转发时,四个域数据都能访问;请求转发后,pageContext的数据丢失,但request、session和application的数据仍然保留。当关闭浏览器,session数据消失,而application数据在web工程运行期间持续存在。重启服务器,所有数据清空。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jsp四大域对象

pageContext (PageContextImpl类) 当前jsp页面范围有效

request (HttpServletRequest)  一次请求有效

session (HttpSession)  一个会话范围内有效(打开浏览器访问服务器,直到关闭浏览器)

application ServletContext对象   整个web工程范围内都有效(只要web工程不停止,数据都在)

一般存储数据优先级会从范围小到大

我们先测试t.jsp,这时候没有请求转发

<%@ page import="java.util.Date" %>


<%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2021/10/3
  Time: 21:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
        //向域对象写入数据
        request.setAttribute("key","request");
        session.setAttribute("key", "session");
        pageContext.setAttribute("key", "pageContext");
        application.setAttribute("key", "application");
        
    %>
request  key的值是<%=request.getAttribute("key")%>
<br>
session  key的值是<%=session.getAttribute("key")%>
<br>
pageContext  key的值是<%=pageContext.getAttribute("key")%>
<br>
application  key的值是<%=application.getAttribute("key")%>
<%--<%  //请求转发到其他页面--%>
<%--    request.getRequestDispatcher("/t1.jsp").forward(request,response);--%>
<%--%>--%>
</body>
</html>

 

 开启服务器访问

 四个域数据都有值

再重启服务器,并开始请求转发到t1.jsp

<%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2021/10/4
  Time: 19:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>t1</title>
</head>
<body>
request  key的值是<%=request.getAttribute("key")%>
<br>
session  key的值是<%=session.getAttribute("key")%>
<br>
pageContext  key的值是<%=pageContext.getAttribute("key")%>
<br>
application  key的值是<%=application.getAttribute("key")%>
</body>
</html>

再次重启服务器

 

发现pageContext key的值是null

再直接从地址栏访问t1

 发现request的域数据也无法访问了

再关闭浏览器,不关闭服务器,再次访问t1.jsp

发现session的域数据也超范围了

再重启服务器,并刷新当前t1页面

 

发现全部为空了 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孔雀南飞梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值