eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – Diagrid – NPI EA (cat= Testing)
announcement - icon

In distributed systems, managing multi-step processes (e.g., validating a driver, calculating fares, notifying users) can be difficult. We need to manage state, scattered retry logic, and maintain context when services fail.

Dapr Workflows solves this via Durable Execution which includes automatic state persistence, replaying workflows after failures and built-in resilience through retries, timeouts and error handling.

In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot:

>> Dapr Workflows With PubSub

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);

    private static final Logger logger = LoggerFactory.getLogger(StoreSessionServlet.class);


    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.

As always, the full code is available over on Github.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

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.

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments