JSP——四大作用域
阿新 • • 發佈:2018-11-12
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>