简介
在JavaWeb中,Servlet中三大域对象分别是request,session,ServletContext,其只要是用来存放共享数据的。html
三大做用域的使用,其本质是根据做用域的范围,生命周期决定其使用的方式.:java
- request:每一次请求都是一个新的request对象,若是在Web组件之间须要共享同一个请求中的数据,只能使用请求转发。
- session:每一次会话都是一个新的session对象,若是须要在一次会话中的多个请求之间须要共享数据,只能使用session。
- application:应用对象,Tomcat 启动到关闭,表示一个应用,在一个应用中有且只有一个application对象,做用于整个Web应用,能够实现屡次会话之间的数据共享。
对象名称 | 对象类型 |
---|---|
request | HttpServletRequest |
session | HttpSession |
application | ServletContext |
三个做用域通用方法
存放数据:setAttribute(name,value)服务器
获取数据:getAttribute(name);session
删除数据:removeAttribute(name);app
application(ServletContext)
做用域
application:应用对象,服务器启动到关闭,表示一个应用。在一个应用中有且只有一个application对象,做用于整个Web应用,能够实现屡次会话之间的数据共享。jsp
生命周期
建立:服务器启动时为每个项目建立一个上下文对象(ServletContext)
销毁:服务器关闭的时候 或者项目移除的时候ide
session(HttpSession)
做用域
生命周期
建立 : 第一次调用 request.getsession()this
html: 不会
jsp: 会 getSession();
servlet: 会url
销毁 :spa
- 默认30分钟之后
- 服务器关闭的时候
- session.invalidate() 手动销毁
request(HttpServletRequest)
做用域
每一次请求都是一个新的request对象,若是在Web组件之间须要共享同一个请求中的数据,只能使用请求转发。
生命周期
建立 : 请求开始的时候建立(访问服务器资源)。
访问 html: 会
访问 jsp: 会
访问 servlet : 会
销毁 : 响应开始的时候(资源请求结束)。
使用示例
项目启动器
@SpringBootApplication @ServletComponentScan public class ServletApplication { public static void main(String[] args) { SpringApplication.run(ServletApplication.class,args); } }
定义两个Servlet,采用Servlet3.0 注解
设置做用域数据
@WebServlet(name = "MyServlet01",urlPatterns = "/test01") public class MyServlet01 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // application System.out.println("Servlet name is "+this.getServletName()); ServletContext servletContext = req.getServletContext(); servletContext.setAttribute("111","1111"); //session HttpSession session = req.getSession(); session.setAttribute("222","2222"); //request req.setAttribute("333","3333"); resp.getWriter().println("set scope attributes -----"); } }
获取做用域数据
@WebServlet(name = "MyServlet02",urlPatterns = "/test02") public class MyServlet02 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().println("get attributes from 3 scopes -----"); //application(ServletContext) ServletContext servletContext = req.getServletContext(); resp.getWriter().println(servletContext.getAttribute("111")); //session HttpSession session = req.getSession(); resp.getWriter().println(session.getAttribute("222")); //request resp.getWriter().println(req.getAttribute("333")); } }