四个域在使用的时候,优先顺序分别是,他们从小到大的范围的顺序。
pageContext ====>>> request ====>>> session ====>>> application
测试
scope.jsp 页面
<body>
<h1>scope.jsp 页面</h1>
<%
// 往四个域中都分别保存了数据
pageContext.setAttribute("key", "pageContext");
request.setAttribute("key", "request");
session.setAttribute("key", "session");
application.setAttribute("key", "application");
%>
pageContext 域是否有值:<%=pageContext.getAttribute("key")%> <br>
request 域是否有值:<%=request.getAttribute("key")%> <br>
session 域是否有值:<%=session.getAttribute("key")%> <br>
application 域是否有值:<%=application.getAttribute("key")%> <br>
<%
request.getRequestDispatcher("/scope2.jsp").forward(request,response);
%>
</body>
scope2.jsp 页面
<body>
<h1>scope2.jsp 页面</h1>
pageContext 域是否有值:<%=pageContext.getAttribute("key")%> <br>
request 域是否有值:<%=request.getAttribute("key")%> <br>
session 域是否有值:<%=session.getAttribute("key")%> <br>
application 域是否有值:<%=application.getAttribute("key")%> <br>
</body>
结果显示
如果直接访问context1.jsp 文件,则结果如下
说明当前页面属于这是四个类
测试request 作用域步骤:
- 在scope1.jsp 文件中添加转发到scope2.jsp(有数据)
因为 pageContext 的数据是在 scope1.jsp 中存储的且pageContext的左右范围只有当前page。而由于是scope1转发给scope2,所以scope2的request有结果。 - 因此,如果不通过scope1转发到scope2,而是直接访问scope2,那么request就会为空
测试session 作用域步骤:
- 访问完context1.jsp 文件
- 关闭浏览器。但是要保持服务器一直开着
- 打开浏览器,直接访问context2.jsp 文
测试application 作用域步骤:
- 访问完context1.jsp 文件,然后关闭浏览器
- 停止服务器。再启动服务器。
- 打开浏览器访问context2.jsp 文件