1. ServletContext:范围最大,应用程序级别的,整个应用程序都能访问;
2. HttpSession–次之,会话级别的,在当前的浏览器中都能訪问[不论是在同一浏览器开多少窗体,都能够访问],可是换个浏览器就不行了,
就必须又一次创建session;
3. HttpServletRequest–范围最小,请求级别,请求结束,变量的作用域也结束【也就是仅仅是一次访问,访问结束,这个也结束】。
如:
/** * 在Servlet中懂得ServletContext HttpSession 以及HttpServletRequest之间的关系: * ServletContext–范围最大,应用程序级别的,整个应用程序都能访问 * HttpSession–次之,会话级别的,在当前的浏览器中都能訪问[不论是在同一浏览器开多少窗体,都能够访问],可是换个浏览器就不行了。 * 就必须又一次创建session * HttpServletRequest –范围最小,请求级别,请求结束,变量的作用域也结束[也就是仅仅是一次访问,访问结束,这个也结束] * * @param request * @param response * @return */ @RequestMapping("/testServlet") public ResponseBean testServlet(HttpServletRequest request, HttpServletResponse response) { // 1 ServletContext sc = request.getServletContext(); sc.setAttribute("sc_name", "sc_value"); // 2 HttpSession session = request.getSession(); session.setAttribute("session_name", "session_value"); // 3 request.setAttribute("request_name", "request_value"); String sc_value = (String) sc.getAttribute("sc_name"); String session_value = (String) session.getAttribute("session_name"); String request_value = (String) request.getAttribute("request_name"); log.debug(sc_value + ":" + session_value + ":" + request_value); // request.getRequestDispatcher("MyServlet2").forward(request, response); return ResponseBean.buildSuccessResponse(); } @RequestMapping("/testServlet2") public ResponseBean testServlet2(HttpServletRequest request, HttpServletResponse response) { // 1 ServletContext sc = request.getServletContext(); // 2 HttpSession session = request.getSession(); String sc_value = (String) sc.getAttribute("sc_name"); String session_value = (String) session.getAttribute("session_name"); String request_value = (String) request.getAttribute("request_name"); log.debug(sc_value + ":" + session_value + ":" + request_value); // request.getRequestDispatcher("MyServlet2").forward(request, response); return ResponseBean.buildSuccessResponse(); }