Java HttpSession Object Storage
In Java web applications, maintaining user state across multiple requests is essential. Since HTTP is a stateless protocol, we use HttpSession to store user-specific data. One powerful feature of HttpSession is that it allows storing complete Java objects, not just primitive values or strings. Let us delve into understanding how to use Java HttpSession to store objects for managing user-specific data across multiple requests in web applications.
1. Understanding HttpSession in Java
HttpSession is an interface provided by the Java Servlet API that enables web applications to maintain user-specific state and data across multiple HTTP requests. Since HTTP is a stateless protocol, every request sent from the browser is treated as a completely new request by the server. To solve this limitation, HttpSession helps applications preserve user information such as login details, shopping cart items, user preferences, authentication tokens, and temporary application data throughout a user session.
A session is automatically associated with a unique session identifier called JSESSIONID, which is usually stored inside browser cookies. Whenever the same client sends another request, the session ID is sent back to the server so that the previously stored session data can be retrieved. Developers can create, access, update, and remove session attributes using methods such as setAttribute(), getAttribute(), and removeAttribute().
To learn more about session creation and management methods, refer to: Jakarta Servlet Specification and HttpSession API Documentation.
- Each user gets a unique session ID (
JSESSIONID) for tracking client requests - Session data is stored on the server side, making it more secure than client-side storage
- It persists until session timeout, browser closure, or manual invalidation using
session.invalidate() - Supports storing primitive values, collections, and complete Java objects
- Helps maintain authentication and authorization state in web applications
- Works seamlessly with Servlets, JSP, and frameworks like Spring MVC and Spring Boot
- Session attributes can be accessed across multiple servlets and JSP pages during the same user session
2. HttpSession Object Management Example
Below is a complete working example demonstrating how a Java object is stored, retrieved, and removed using HttpSession in a Servlet-based web application. The code also includes logging statements to help trace execution flow in server logs. To run this example, you need the Servlet API dependency.
2.1 Required Dependency
If you are using Maven, add the following dependency in your pom.xml:
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>stable__jar__version</version> <scope>provided</scope> </dependency>
2.2 Servlet Code Example
import java.io.IOException;
import javax.servlet. * ;
import javax.servlet.http. * ;
// USER BEAN
class User {
private String name;
private int age;
public User(String name, int age) {
System.out.println("[User] Creating User object -> " + name + ", " + age);
this.name = name;
this.age = age;
}
public String getName() {
System.out.println("[User] getName() called");
return name;
}
public int getAge() {
System.out.println("[User] getAge() called");
return age;
}
}
// STORE SERVLET
public class StoreSessionServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException {
System.out.println("\n[StoreSessionServlet] Request received");
User user = new User("John Doe", 28);
HttpSession session = request.getSession();
System.out.println("[StoreSessionServlet] Session ID: " + session.getId());
session.setAttribute("userObject", user);
System.out.println("[StoreSessionServlet] User object stored in session");
response.getWriter().println("User object stored in session successfully!");
}
}
// GET SERVLET
class GetSessionServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException {
System.out.println("\n[GetSessionServlet] Request received");
HttpSession session = request.getSession(false);
if (session != null) {
System.out.println("[GetSessionServlet] Session found: " + session.getId());
User user = (User) session.getAttribute("userObject");
if (user != null) {
System.out.println("[GetSessionServlet] User object found in session");
response.getWriter().println("Name: " + user.getName());
response.getWriter().println("Age: " + user.getAge());
} else {
System.out.println("[GetSessionServlet] User object NOT found in session");
response.getWriter().println("User object not found in session!");
}
} else {
System.out.println("[GetSessionServlet] No session found");
response.getWriter().println("No session found!");
}
}
}
// REMOVE SERVLET
class RemoveSessionServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException {
System.out.println("\n[RemoveSessionServlet] Request received");
HttpSession session = request.getSession(false);
if (session != null) {
System.out.println("[RemoveSessionServlet] Session found: " + session.getId());
session.removeAttribute("userObject");
System.out.println("[RemoveSessionServlet] User object removed from session");
response.getWriter().println("User object removed from session.");
} else {
System.out.println("[RemoveSessionServlet] No session available");
response.getWriter().println("No session available.");
}
}
}
2.2.1 Code Explanation
This code demonstrates how to store, retrieve, and remove a Java object in HttpSession using Java Servlets. First, a simple Java Bean class named User is created with two private fields, name and age, along with a constructor to initialize these values and getter methods (getName() and getAge()) to access them, which is important because session storage relies on serializable object data and encapsulation. Next, the StoreSessionServlet class extends HttpServlet and overrides the doGet() method, where a new User object is created with sample values “John Doe” and 28; then request.getSession() is used to either create a new HTTP session or fetch the existing one, and the object is stored inside the session using session.setAttribute("userObject", user), meaning the user object is now saved on the server and associated with that client session, and a response message confirms successful storage. After that, the GetSessionServlet is used to retrieve the same object, where request.getSession(false) ensures that a new session is not created if one does not exist; if a valid session is found, the stored object is fetched using session.getAttribute("userObject") and typecast back to the User class because session attributes are stored as generic Objects, and then the values are printed using getter methods, while proper null checks ensure safe handling when either session or object is missing. Finally, the RemoveSessionServlet handles cleanup by again fetching the session using getSession(false) and then calling session.removeAttribute("userObject") to delete only the stored object without invalidating the entire session, allowing other session data to remain intact, and appropriate response messages are returned depending on whether the session exists or not; overall, this flow shows how HttpSession acts as server-side storage to maintain user state across multiple HTTP requests in a stateless web environment.
2.2.2 Application Execution and Output
When this application is deployed on a servlet container like Tomcat or run using a Spring Boot embedded server, each servlet is triggered through a specific URL mapping (for example: /store, /get, and /remove).
First, when the StoreSessionServlet is executed by hitting its endpoint in the browser or Postman, the server creates a User object with values “John Doe” and age 28, then stores it inside the HttpSession using setAttribute(). At this point, the session is created (if it does not already exist) and the response message “User object stored in session successfully!” is returned to confirm that the object is safely stored on the server side. In the server logs, you can also observe execution traces like session creation, session ID generation, and object storage confirmation, which helps verify that the state is being maintained correctly on the backend.
[StoreSessionServlet] Request received [User] Creating User object -> John Doe, 28 [StoreSessionServlet] Session ID: A1B2C3D4 [StoreSessionServlet] User object stored in session
Next, when the GetSessionServlet is called using the same session (maintained via JSESSIONID cookie), the servlet retrieves the stored object using getAttribute("userObject"), casts it back to the User class, and prints the stored values. Therefore, the output displayed in the browser will be “Name: John Doe” and “Age: 28”, provided the session is still active and the object has not been removed. In the logs, you will also see debug-style messages confirming session retrieval, object lookup, and method calls like getName() and getAge(), which help trace how the object is being accessed during runtime.
[GetSessionServlet] Request received [GetSessionServlet] Session found: A1B2C3D4 [User] getName() called [User] getAge() called [GetSessionServlet] User object found in session
Finally, when the RemoveSessionServlet is executed, the stored object is deleted using removeAttribute(), and the response “User object removed from session.” is returned. After this operation, any subsequent call to the Get servlet will result in either “User object not found in session!” or “No session found!” depending on whether the session still exists or has expired. In the logs, this step clearly shows confirmation of attribute removal, ensuring that the session state is properly cleaned up. Overall, this demonstrates the complete lifecycle of session-based object management—creation, retrieval, and deletion—along with clear runtime visibility through server-side logs in a stateless HTTP environment.
[RemoveSessionServlet] Request received [RemoveSessionServlet] Session found: A1B2C3D4 [RemoveSessionServlet] User object removed from session
3. Conclusion
HttpSession is a powerful mechanism in Java Servlets to maintain user state across multiple requests. By storing Java objects in session, developers can easily manage complex user data such as login information, shopping carts, or preferences. However, developers should use sessions carefully to avoid memory overhead and always invalidate sessions when they are no longer needed.

