Servlet Lesson 6: Session usage
Course objectives:
In this lesson, we can learn to add sessions, call sessions, and understand the existence of sessions.
Course details:
1. The Session only exists in the browser. For example, if we open the browser to get the session we need, and we open it again in the same browser, the session we need still exists.
However, if we switch to another browser or directly close the browser, the session will expire.
2. Session
-Session is a mechanism used to track the current status of users. It is a one-to-one relationship between browsers and servers.
-Session is generally used to save the user's logon information to the session for later use.
3. Session interface HttpSession
Generally, we only use the HttpSession interface. The implementation of the interface is completed by the web container.
-You can obtain HttpSession from HttpServletRequest.
Request. getSession ();
-Save the information in HttpSession
Session. setAttribute ("UserSession", obj); [Note: You can directly store the obj object. For example, you can directly store a user object here]
-Obtain information from HttpSession
Session. getAttribute ("UserSession ");
-Invalidate HttpSession
Session. invalidate ();
4. Examples:
In fact, I think the use of this session is similar to that of cookies.
Set Session Servlet
Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session = request. getSession (); session. setAttribute ("session_name", "session_value");} Get Session Servletprotected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session Session = request. getSession (); String value = (String) session. getAttribute ("session_name"); System. out. println (value );}
5. log on to the Session instance.
Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub // in order to obtain data transmitted from the foreground: username and password String username = request. getParameter ("username"); String password = request. getParameter ("password"); // call the dao implementation logic: for example, verify whether the user account and password are correct. // If yes, query all required information through username and password, and then encapsulate it into a user object UserDao dao = new UserDaoImpl ( ); User u = dao. login (username, password); if (u! = Null) {// judgment. If a user exists, it encapsulates a user object and sends it to jspHttpSession session = request. getSession (); session. setAttribute ("user", u); request. getRequestDispatcher ("welcome. jsp "). forward (request, response);} else {// judge. If the user does not exist, go directly to the error page request. getRequestDispatcher ("error.html "). forward (request, response );}}