JSP——四大作用域

pageContext
作用于当前页面 生命周期太短,不常用

request
作用于一次请求
1,ajax 不会打断一次请请求
2,JSP:forword不会打断一次请求
3,服务器内部的跳转不会打断一次请求

1,a标签会打断一次请求
2,用户执行的操作引起页面跳转会打断一次请求

session
作用于一次会话 会话有时间的限制

application
作用于整个服务器,如不关闭服务器一直存在

例子:
A.jsp

<%@page import="java.util.Calendar"%>
<%@ 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">
</head>
<body>
<%
  pageContext.setAttribute("pageContextKey", Calendar.getInstance());

  request.setAttribute("requestKey", Calendar.getInstance());
  
  session.setAttribute("sessionKey", Calendar.getInstance());
  
  application.setAttribute("applicationKey", Calendar.getInstance());
%>
<%
	out.print(pageContext.getAttribute("pageContextKey"));
	out.print("<br />");
	out.print(request.getAttribute("requestKey"));
	out.print("<br />");
	out.print(session.getAttribute("sessionKey"));
	out.print("<br />");
	out.print(application.getAttribute("applicationKey"));
%>

<jsp:forward page="B.jsp" />
</body>
</html>

B.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>
<% 
	out.print(pageContext.getAttribute("pageContextKey"));
	out.print("<br />");
	out.print(request.getAttribute("requestKey"));
	out.print("<br />");
	out.print(session.getAttribute("sessionKey"));
	out.print("<br />");
	out.print(application.getAttribute("applicationKey"));
%>
<a href="C.jsp">GOGOGOGOGOGOGOGOGOGOGOGOGOGOGOGOGO</a>
</body>
</html>

C.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>
<% 
	out.print(pageContext.getAttribute("pageContextKey"));
	out.print("<br />");
	out.print(request.getAttribute("requestKey"));
	out.print("<br />");
	out.print(session.getAttribute("sessionKey"));
	out.print("<br />");
	out.print(application.getAttribute("applicationKey"));
%>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/footprint01/article/details/82971445