作用域:存放数据,获取数据(传递数据)
servlet里面的三大作用域
- a:生命周期
- b:作用范围
- c:提到作用域要想到三个方式 get,set,remove
<h3>HttpServletRequest作用域</h3>
<ol>
<li>生命周期:一次请求之间</li>
<li>作用范围:所有被请求转发过的servlet都可以获取到</li>
</ol>
<a href="HelloRequest">HttpServletRequest作用域</a>
<h3>HttpSession作用域</h3>
<ol>
<li>生命周期:一次会话之间</li>
<li>作用范围:只要设置一次session,所有的servlet都能获取到</li>
</ol>
<a href="HelloSession">HttpSession作用域</a>
<h3>ServletContext作用域</h3>
<ol>
<li>生命周期:从服务器启动到服务器停止</li>
<li>作用范围:只要设置一次servletContext作用域,所有的servlet都能获取到</li>
</ol>
<a href="HelloServeletContext">ServletContext作用域</a>
如何选用?
HttpServletRequest作用域:和本次请求有关的数据
HttpSession作用域:和当前用户有关的数据
ServletContext作用域:经常被访问到,不易修改的数据(地址)
作用域设置方式
//reuqest设置作用域
req.setAttribute(“requestScope”, “request-Scope”);
//在session作用域存储数据
req.getSession().setAttribute(“httpsessionScope”, “HttpSession-Scope”);
//设置servletContext作用域
this.getServletContext().setAttribute(“servletContextScope”, “servletContext-Scope”);
作用域取值方式
//获取request作用域里面的值
String requestscope = (String) req.getAttribute(“requestScope”);
System.out.println(“HelloTestScope.service(HttpServletRequest作用域):”+requestscope);
//获取session作用域里面的值
String sessionScope = (String) req.getSession().getAttribute(“httpsessionScope”);
System.out.println(“HelloTestScope.service(HttpSession作用域):”+sessionScope);
//获取ServletContext作用域里面的值
String servletContextScope = (String) this.getServletContext().getAttribute(“servletContextScope”);
System.out.println(“HelloTestScope.service(ServletContext作用域):”+servletContextScope);