How to Get a Session?
We can keep track of a client’s session with the HttpSession object. In Java Servlets, the HttpSession interface provides a way to regulate the state/information about a user varying across multiple requests. It is a part of javax.servlet.http package and allows storing and retrieving the attributes about the user’s information, providing a mechanism for session management.
Retrieving HttpSession in Servlets
We can use the getSession() method to create a HttpSession object. The getSession() method returns a session if it already exists or creates a new one, in case no session exists. The following snippet follows.
HttpSession session = request.getSession();
Using the parameterized getSession(boolean) method, it returns a new session if we pass the true parameter. The syntax will look something like this.
HttpSession session = request.getSession(true);
Further, to fetch a pre-existing session, one can pass false in the parameterized getSession() method.
HttpSession session = request.getSession(false);
Session Management in Java
Session is used to save user information momentarily on the server. It starts from the instance the user logs into the application and remains till the user logs out of the application or shuts down the machine. In both cases, the session values are deleted automatically. Hence, it functions as a temporary storage that can be accessed till the user is active in the application and can be accessed when the user requests a URI. This session is stored in binary values, hence maintaining the security aspect, and can be decoded only at the server end.
Contact Us