Course objectives:
① Understand the relationship between servletcontext httpsession and httpservletrequest in Servlet
② Understand how to use them
Concepts:
1. [commonalities] regardless of the scope of the object, the shared variables and methods for obtaining variables are consistent.
-Setattribute ("varname", OBJ );
-Getattribute ("varname ");
2. Scope of Variables
Servletcontext-Maximum range, application-level, all applications can access
Httpsession-second, the session level can be accessed in the current browser [no matter how many windows are opened in the same browser], but it will not work if you change the browser, you must re-create the session
Httpservletrequest-minimum range, request level, request end, and variable scope [that is, only one access, access is complete, and this is also done]
3. Instance
The preceding three data settings are as follows:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1 ServletContext sc = this.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"); System.out.println(sc_value+":"+session_value+":"+request_value); // request.getRequestDispatcher("MyServlet2").forward(request, response); }
Obtain servlet2:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc = this.getServletContext(); 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"); System.out.println(sc_value+":"+session_value+":"+request_value);}
Conclusion:
Httpservletrequest is only a browser access, unless the servlet is processed, such
request.getRequestDispatcher("MyServlet2").forward(request, response);
It will be passed.
Sessions are used in the same browser to call data from each other.
The entire application of servletcontext can access