Managing Data Within the HttpSession Scope
Scope Validity
Data stored in the HttpSession object remains accessible throughout the duration of a user's interaction with the web application. It persists across multiple request-response cycles within a single browser sesssion.
Lifecycle Events
- Initialization: The container creates a session object when a request is made and the session does not already exist.
- Active Usage: The session remains valid while the user interacts with the application. The server maintains this state across different pages or resources.
- Termination: The session ends when the browser closes (losing the session ID cookie), the server invalidates it manually, or the session times out due to inactivity.
Implementation Examples
Storing Attributes
The following servlet demonstrates initializing a session and populating it with various attributes, including a collection of values.
package com.example.webapp;
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;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@WebServlet("/saveData.action")
public class SessionWriter extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Retrieve or create the current session context
HttpSession userSession = request.getSession();
// Prepare a list of items
List<String> items = Arrays.asList("Alpha", "Beta", "Gamma");
userSession.setAttribute("itemCollection", items);
// Store simple string attributes
userSession.setAttribute("userRole", "Administrator");
userSession.setAttribute("status", "Active");
userSession.setAttribute("username", "JohnDoe");
// Forward the request to the reader servlet
response.sendRedirect("loadData.action");
}
}
Retrieving Attributes
This servlet reads the data previously stored in the session and outputs it to the console.
package com.example.webapp;
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;
import java.io.IOException;
import java.util.List;
@WebServlet("/loadData.action")
public class SessionReader extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession userSession = request.getSession();
// Optional: Remove a specific attribute from the session
// userSession.removeAttribute("status");
// Extract attributes from the session scope
List<String> retrievedItems = (List<String>) userSession.getAttribute("itemCollection");
String role = (String) userSession.getAttribute("userRole");
String user = (String) userSession.getAttribute("username");
// Log the session data
System.out.println("Retrieved List: " + retrievedItems);
System.out.println("User Role: " + role);
System.out.println("Username: " + user);
// Extract parameters specifically from the current HTTP request (not session)
System.out.println("Query Param 'id': " + request.getParameter("id"));
System.out.println("Query Param 'type': " + request.getParameter("type"));
}
}