Example of Session Management
Below example demonstrates creating a session, setting and retrieving attributes, and finally, invalidating the session.
Java
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet ( "/api" ) public class GFG extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the HttpSession object. If it doesn't exist, a new one will be created. HttpSession session = request.getSession(); // Set a session attribute session.setAttribute( "username" , "GFG" ); // Retrieve the session attribute String username = (String) session.getAttribute( "username" ); // Display the attribute value in the response response.getWriter().println( "Username from Session: " + username); // Invalidate the session after displaying the attribute session.invalidate(); } } |
Explaination of the above Example:
- A servlet named /api is created.
- When a user accesses the servlet, the doGet method is called which retrieves the existing HttpSession associated with the request or creates a new one if it doesn’t exist using the request.getSession() method.
- The servlet sets a session attribute named “username” to the value “GFG” using session.setAttribute.
- It retrieves the “username” attribute from the session using session.getAttribute and prints it in the HTTP response.
- Finally, the session.invalidate() method is called to invalidate the session.
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