Spring Boot @SessionAttribute Example

1. Introduction

The @SessionAttributes annotation in Spring MVC is designed to store model attributes in the session. It is particularly useful in wizard-like scenarios where form data is to be persisted across multiple requests.

Key Points:

1. @SessionAttributes is used at the controller class level to store certain model attributes in the HTTP session.

2. It allows for cross-request usage of model attributes, avoiding the need for hidden form fields or manual session management.

3. Attributes in the session can be accessed and manipulated across multiple controller methods or even different controllers.

2. Implementation Steps

1. Annotate a controller class with @SessionAttributes and specify the name of the model attribute to be stored in the session.

2. Use @ModelAttribute at method level to add attributes to the model.

3. Create controller methods to handle HTTP requests and manipulate the session attributes.

4. Implement methods to retrieve and clear the session attributes when done.

5. Run the application and navigate through the controller to test session persistence.

3. Implementation Example

Here is the complete code that demonstrates the usage of @SessionAttribute annotation:
// Step 1: Annotate the controller class with @SessionAttributes
@Controller
@SessionAttributes("counter")
public class CounterController {

    // Step 2: Initialize the counter and store it in the session when the session starts
    @ModelAttribute("counter")
    public AtomicInteger initCounter() {
        return new AtomicInteger();
    }

    // Step 3: Create a method to increment the counter
    @GetMapping("/increment")
    public String incrementCounter(@ModelAttribute("counter") AtomicInteger counter, Model model) {
        counter.incrementAndGet();
        model.addAttribute("counter", counter.get());
        return "counterView";
    }

    // Step 4: Create a method to clear the session attribute
    @GetMapping("/clear")
    public String clearCounter(SessionStatus status) {
        status.setComplete();
        return "redirect:/increment";
    }
}

// Step 5: Create the main application class
@SpringBootApplication
public class SessionAttributeExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(SessionAttributeExampleApplication.class, args);
    }
}

// Assume that 'counterView.html' is a Thymeleaf template present in 'src/main/resources/templates'

Output:

// When visiting /increment, the number increments with each request:
Counter: 1
Counter: 2
Counter: 3
...
// After visiting /clear, the counter resets:
Counter: 1

Explanation:

1. @SessionAttributes("counter") specifies that the counter model attribute should be stored in the HTTP session.

2. @ModelAttribute("counter") ensures an AtomicInteger is placed in the model and the session when a new session starts.

3. The incrementCounter method is mapped to /increment and increments the counter each time it's called.

4. @ModelAttribute("counter") AtomicInteger counter pulls the current counter from the session so it can be incremented.

5. The clearCounter method is mapped to /clear and ends the session, effectively clearing the counter by calling status.setComplete().

6. SessionAttributeExampleApplication contains the main method to run the application.

7. The output indicates that with each visit to /increment, the counter in the session increments and is displayed in the counterView. Visiting /clear resets the session attribute, starting the counter over.


Comments