1.page
作用范围:只能在当前页面
2.Request
作用范围:当前请求周期,也可以说request的有效范围为同一个请求,通俗的说就是使用同一个request对象的都有效request为常用的作用域(页面间或者servlet与jsp之间的跳转),但是注意转发和重定向问题
3.Session
当前会话。所谓当前会话,就是指从用户打开浏览器开始,到用户关闭浏览器这中间的过程。这个过程可能包含多个请求响应。一般常用于存放用户的登录信息。在不同页面都起作用,但是换一个浏览器就不行了。
4.Application
作用范围:最广,整个应用都可以。
测试:
javaservlet.jsp:
<body>
<%
//测试page作用域
pageContext.setAttribute("aaa", "测试page作用域");
request.setAttribute("bbb", "测试request作用域");
//request.getRequestDispatcher("testServlet.jsp").forward(request, response);
session.setAttribute("ccc", "测试session作用域");
pageContext.getServletContext().setAttribute("ddd", "测试application作用域");
%>
page:<%=pageContext.getAttribute("aaa") %></br>
request:<%=request.getAttribute("bbb") %></br>
session:<%=session.getAttribute("ccc") %></br>
application:<%=pageContext.getServletContext().getAttribute("ddd") %>
</body>
testServlet.jsp
<body>
page:<%=pageContext.getAttribute("aaa") %></br>
request:<%=request.getAttribute("bbb") %></br>
session:<%=session.getAttribute("ccc") %></br>
application:<%=pageContext.getServletContext().getAttribute("ddd") %>
</body>
运行结果:
当前页面中,四大作用域都起作用
第二个跳转页面中只有session、Application起作用
要想使request起作用需要进行页面转发,使两次请求共用同一个request
request.getRequestDispatcher("testServlet.jsp").forward(request, response);
添加页面转发后我们发现request作用域生效,由于是request请求,所以不会在地址栏上发生变化,但是我们可以看到page作用域失效,说明页面已经发生了跳转testServlet.jsp中。
我们换一个浏览器输入地址,session失效
总结:四大作用域
作用范围:Application>Session>Request>Page