JSP 中request、session 与 application 的区别

本文介绍了request、session和application三种不同作用域的区别,并通过一个简单的示例代码演示了它们在实际应用中的生命周期特点。

三者区别:

request:就像发短信,request生命周期跟同一个请求同生死。
session:就像打电话,在一个会话中都有效。session跟同一个浏览器的打开与关闭同生死。
application:跟同一个应用相关,只跟服务器的打开与关闭同生死,跟浏览器无关(除非重启服务器,否则application的数据不会丢失)。

测试:设置了 session1.jsp 和 session2.jsp 两个文件,点击 session1.jsp 中的超链接标签跳转到 session2.jsp ,代码如下:

session1.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
    <%
       request.setAttribute("requestTestKey", "requestTestVal");
       session.setAttribute("sessionTestKey","sessionTestVal");
       application.setAttribute("applicationKey","applicationVal");   
    %>
    <a href="session2.jsp">点我到session2.jsp</a>
</body>
</html>

session2.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
   <%
     String requestVal = (String)request.getAttribute("requestTestKey");
     String sessionVal = (String)session.getAttribute("sessionTestKey");
     String applicationVal = (String)application.getAttribute("applicationKey");
 
     out.print(requestVal);
     out.print("<br/>");
     out.print(sessionVal);
     out.print("<br/>");
     out.print(applicationVal);
   %>
</body>
</html>


可以运行代码查看区别。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值