Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

When developing Java-based web applications, there are many situations where we need to maintain user-related data between HTTP requests. HTTP is a stateless protocol and does not maintain any information between requests. This means that each HTTP request is independent and has no prior knowledge of the other requests made for the same session.

In this tutorial, we’ll discuss the basic concepts related to the HttpSession interface in detail. We’ll also discuss the process of storing, retrieving, and deleting Java objects using the key methods provided by the interface, such as setAttribute(), getAttribute(), and removeAttribute().

2. What Is HttpSession?

The HttpSession interface is a part of the javax.servlet.http package. It’s used to store a user’s data on the server side between multiple HTTP requests. HTTP is a stateless protocol. HttpSession fills the gap between HTTP’s statelessness and the need to store a user’s data on the server side by providing a unique session to each user.

The servlet container manages the creation of sessions and tracks them using a unique session ID stored as a cookie named JSESSIONID in the client’s browser. We can access a session from any servlet using the getSession() method of the HttpServletRequest object. Let’s see an example of obtaining a session:

HttpSession session = request.getSession(); 

The request.getSession() method will return the existing active session if one has already been created. Otherwise, it’ll create a brand new one. We can also send the value false as a parameter: request.getSession(false). This allows us to get the existing session without creating a new one. Once we have the session object, we’re ready to start storing data in it.

3. Storing a Java Object in HttpSession

The Java object is stored within a session by means of a setAttribute() method provided by an HttpSession interface. The method takes two parameters: a String key and an object to be stored. This makes it easy to associate any Java object with a key for later retrieval.

Let’s say we have a User class and we want to store a logged-in user’s data in the session. First, here’s our simple User class:

public class User implements Serializable {
    private String username;
    private String email;

    public User(String username, String email) {
        this.username = username;
        this.email = email;
    }

    public String getUsername() { return username; }
    public String getEmail() { return email; }
}

Now, here’s how we store an instance of this object in the session inside a servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

    User user = new User("john_doe", "[email protected]");

    HttpSession session = request.getSession();

    session.setAttribute("loggedInUser", user);
}

In this example, we first create a new User object with a username and email. Then, we call request.getSession() to obtain the current session. After that, we use session.setAttribute(“loggedInUser”, user) to store the object under the key “loggedInUser”. From this point on, any servlet or JSP in the same session can access this object using that exact key.

4. Retrieving a Java Object from HttpSession

Once we have stored an object in the session, we need a reliable mechanism to access it in the next request. The getAttribute() function provides exactly that purpose. It returns the corresponding object given a key used in the setAttribute() function. And so, it enables us to access the user’s data throughout the entire session.

Building on our previous example, here’s how we retrieve the stored User object in another servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
 
    HttpSession session = request.getSession(false);
 
    if (session != null) {
        User user = (User) session.getAttribute("loggedInUser");

        if (user != null) {
            logger.info("Welcome back, " + user.getUsername());
        } else {
            logger.info("No user found in session.");
        }
    } else {
        logger.info("No active session found.");
    }
}

First, we begin with a call to request.getSession(false) to obtain the current session without accidentally opening a new session. Then, we retrieve the stored object via session.getAttribute(“loggedInUser”), casting it to User. The key point is to always check that it is not null. For example, a session has timed out, or maybe we haven’t yet set the attribute. So, a simple null check is a common pattern to keep our code safe from potential NullPointerException issues.

5. Removing an Object from HttpSession

At some point, we’ll have to clean up the session data that’s no longer required. For example, we clear the user’s details when the user logs out or clear a specific attribute. The HttpSession interface provides two ways of doing it: removeAttribute(), which removes a specific object, and invalidate(), which clears the session.

Here’s how we use both in practice:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

    HttpSession session = request.getSession(false);

    if (session != null) {

        session.removeAttribute("loggedInUser");

        session.invalidate();
    }
}

In this example, we begin by retrieving the existing session through request.getSession(false). Then, we remove the existing User object we previously stored by calling session.removeAttribute(“loggedInUser”), leaving all other session data intact. session.invalidate() removes the entire session, clearing all the data contained within the session from memory. Moreover, it is important to include a null check to avoid errors when there is no active session.

6. Conclusion

In this article, we’ve discussed how to manage Java objects within an HttpSession using three basic operations: setAttribute to put objects into the session, getAttribute to retrieve objects from the session, and removeAttribute to clean up specific objects from the session. As you can see, we have good control over objects stored within a session and can use this to build stateful, user-aware web applications using the stateless HTTP protocol.

Beyond the basics, we also saw why careful session handling matters. We perform null checks when retrieving attributes and call invalidate() on logout to prevent stale data from lingering on the server. With these fundamentals in place, we’re able to tackle real-world session management challenges and build Java web applications that are both robust and secure.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW