Java Session Management Guide
In Java, Session is a mechanism used to store user state information between the client and server, which can be stored either on the server side or on the client side.
The typical steps involved in using Session in Java usually include the following:
-
To obtain a Session object:
In a Servlet, you can acquire a Session object by calling the getSession() method of the HttpServletRequest object, as shown below:
HttpSession session = request.getSession();
- Storing data in Session:
You can store data in Session by using the setAttribute() method of the Session object, as shown below:
session.setAttribute("username", "john");
- To retrieve data from a Session:
You can use the getAttribute() method of the Session object to retrieve data from the Session, as shown below:
String username = (String) session.getAttribute("username");
- To remove data from the session:
You can use the removeAttribute() method of the Session object to delete data from the session, as shown below:
session.removeAttribute("username");
- To establish the session timeout:
You can set the session timeout using the setMaxInactiveInterval() method of the Session object (in seconds), as shown below:
session.setMaxInactiveInterval(60); // 设置Session超时时间为1分钟
- Destroying Session:
You can destroy a session using the invalidate() method of the Session object, as shown below:
session.invalidate();
Using the above method, you can save user state information in Java to achieve functions like user session management.