1,作用域:共享数据的区域
如request就是一个作用域对象,request.setAttribute()和getAttribute()在请求作用域中保存和读取数据。
pageContext
当前页对象。共享数据的范围为当前页面。
如果不在一个页面,数据无法读取。
request***
请求对象。共享数据的范围为一次请求。
只要请求不改变(不重定向),数据一直保存在请求对象中。
session***
会话对象。共享数据的范围为同一个浏览器指定的时间内。
默认会话时长为30分钟,表示如果30分钟没有对该站点进行访问,自动销毁会话。
application
应用程序(项目)对象。共享数据的范围为整个项目中。
作用域作用范围
最大到最小
application >> session >> request >> pageContext
以上的作用域对象,都有这几个方法
//向作用域中保存数据
作用域对象.setAttribute(String str,Object obj);
//读取作用域中保存的数据
Object obj = 作用域对象.setAttribute(String str);
//移除作用域中保存的数据
作用域对象.removeAttribute(String str);
2、作用域对象的使用
在JSP页面中使用
在JSP中,作用域对象为内置对象,无需定义可以直接使用。
p1.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>当前为p1页面</h1>
<%--在页面中,向四个作用域对象中保存数据--%>
<%
pageContext.setAttribute("str","保存在pageContext中的字符串");
request.setAttribute("str","保存在request中的字符串");
session.setAttribute("str","保存在session中的字符串");
application.setAttribute("str","保存在application中的字符串");
%>
<%--当前页中获取数据的情况--%>
<h1><%=pageContext.getAttribute("str")%></h1>
<h1><%=request.getAttribute("str")%></h1>
<h1><%=session.getAttribute("str")%></h1>
<h1><%=application.getAttribute("str")%></h1>
<%--使用a标签跳转,属于重定向,无法获取request中的内容--%>
<a href="p2.jsp">跳转到p2</a>
<%
//手动销毁session,或超时未操作,无法读取其中的数据
//session.invalidate();
//移除指定作用域中保存的数据
application.removeAttribute("str");
//使用请求转发,除pageContext之外的所有作用域中都能获取保存的数据
request.getRequestDispatcher("p2.jsp").forward(request,response);
%>
</body>
</html>
p2.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>当前为p2页面</h1>
<%--当前页中获取数据的情况--%>
<h1><%=pageContext.getAttribute("str")%></h1>
<h1><%=request.getAttribute("str")%></h1>
<h1><%=session.getAttribute("str")%></h1>
<h1><%=application.getAttribute("str")%></h1>
</body>
</html>
在servlet中使用
-
pageContext
servlet中不会使用pageContext,它本身就是一个类,定义成员变量即可
-
request
使用doGet()、doPost()、service()等方法的HttpServletReques参数即可
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //req就是request对象 }
-
session
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //通过req调用getSession()方法获取session对象 HttpSession session = req.getSession(); }
-
application
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //通过getServletContext()方法获取application对象 ServletContext servletContext = getServletContext(); }
总结
-
pageContext对象用于jsp页面中,保存的数据只能在当前页面中使用
-
request对象常用于servlet中保存查询后的集合,使用请求转发跳转到jsp页面中输出集合
-
session对象常用于登录后保存登录的用户,在其他页面中共享用户对象
-
application对象保存共享于整个项目中的数据