三者区别:
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>可以运行代码查看区别。
本文介绍了request、session和application三种不同作用域的区别,并通过一个简单的示例代码演示了它们在实际应用中的生命周期特点。
1985

被折叠的 条评论
为什么被折叠?



