Open In App

Spring MVC @SessionAttributes Annotation with Example

Last Updated : 03 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In the ever-evolving world of web development, a constant challenge is to seamlessly manage data between requests. Enter Spring MVC’s @SessionAttributes annotation, a powerful solution that elegantly manages the session attributes of a Spring application. This markup becomes a lifesaver when certain information must persist throughout the interaction between the user and the web application.

Prerequisites

Before delving into the intricacies of the @SessionAttributes attribute, it’s important to have a solid understanding of Spring MVC, basic web programming concepts, and basic ideas like sessions. In addition, a basic knowledge of Java and Spring Framework would enrich a deeper understanding of the subject.

@SessionAttributes Annotation in Spring MVC

In Spring MVC, session attributes are declared at the class level using the @SessionAttributes annotation. Once these attributes are decorated with this tag, they persist throughout the session. This proves invaluable when there is a need to persist certain data, such as form data or user authentication data, across multiple HTTP requests.

Step by Step Example of Using @SessionAttribute

To have a better understanding of how to use the @SessionAttributes annotation in a Spring MVC application, let’s look at a concrete example.

Step 1: Add Dependency

First, make sure your project includes the essential Spring MVC dependencies. Add the below maven dependency to the pom.xml file:

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10.RELEASE</version>
</dependency>

Step 2: Declare @SessionAttributes at Class Level

Apply the @SessionAttributes annotation at the class level, specifying the attribute name:

@Controller
@SessionAttributes("userData")
public class UserController {
// ...
}

Step 3: Create Model Attribute

Define a method annotated with @ModelAttribute to create the initial session attribute.

@ModelAttribute("userData")
public UserData createUserData() {
return new UserData();
}

Step 4: Use Session Attribute in Request Mapping

Leverage the session attribute in your request mapping method.

Java




@RequestMapping("/user")
public String handleUser(@ModelAttribute("userData") UserData userData) {
    // Business logic for handling user data
    return "userPage";
}


Step 5: Unit Test

Ensure the correctness of your implementation by adding unit tests. For example, using JUnit and Mockito:

Java




@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
  
    @Autowired
    private MockMvc mockMvc;
  
    @MockBean
    private UserDataRepository userDataRepository;
  
    @Test
    public void testHandleUser() throws Exception {
        // Mock repository behavior
        when(userDataRepository.findById(anyLong())).thenReturn(Optional.of(new UserData()));
  
        // Perform the request
        mockMvc.perform(get("/user"))
                .andExpect(status().isOk())
                .andExpect(view().name("userPage"));
    }
}


Step 6: Dependency Injection

Ensure proper dependency injection by configuring your application context.

Java




@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example")
public class WebConfig implements WebMvcConfigurer {
    // Additional configurations if needed
}


Illustration:

Let’s look at a real situation where we want to save user data between requests using the @SessionAttributes annotation:

Java




@Controller
@SessionAttributes("userData")
public class UserController {
  
    @ModelAttribute("userData")
    public UserData createUserData() {
        return new UserData();
    }
  
    @RequestMapping("/user")
    public String handleUser(@ModelAttribute("userData") UserData userData) {
        // Business logic for handling user data
        return "userPage";
    }
}


In this example, the class-level application of @SessionAttributes with the attribute name “userData” ensures that a UserData object is created and maintained in the session. The handleUser method then efficiently manages user data during each request.

Conclusion

Spring MVC’s @SessionAttributes annotation is a great mechanism for managing session attributes, allowing developers to seamlessly handle data persistence across multiple requests. By understanding its usage and seamlessly integrating it into Spring applications, you improve the user experience by preserving relevant information throughout the user’s interaction with your web application.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads