Understanding the @SessionAttributes and @ModelAttribute Annotations in Spring MVC

Alexander Obregon
3 min readAug 23, 2023

--

Image Source

Introduction

Spring MVC, a part of the larger Spring Framework, is a popular choice among Java developers for building web applications. While it provides a plethora of features to handle web requests, understanding the nuances of its annotations is essential for a smooth development experience. In this article, we’ll taking a look at two such annotations: @SessionAttributes and @ModelAttribute.

The @SessionAttributes Annotation

Before understanding @SessionAttributes, let's quickly recap what a session is. In web applications, a session allows you to store user-specific data across multiple HTTP requests. When a user interacts with your application, a unique session is created, and this session persists across various requests made by that user.

The @SessionAttributes annotation in Spring MVC provides an elegant way to store model attributes in a session. This can be particularly useful for multi-page forms or wizards where you want the data to persist across multiple pages.

Example:

@Controller
@SessionAttributes("user")
public class UserController {

@ModelAttribute("user")
public User setUpUserForm() {
return new User(); // this will be stored in the session after the first call
}

@RequestMapping("/userForm")
public String showForm(Model model) {
// Do some operations
return "userForm";
}
}

In the above code, the attribute “user” is stored in the session because of the @SessionAttributes("user") annotation at the class level. This means that once the user object is added to the model, it will persist across different requests until the session expires or is terminated.

Things to Remember:

  • @SessionAttributes is defined at the class level, ensuring attributes specified in this annotation are stored in the session.
  • To clear the session attributes, you can use the SessionStatus object and call its setComplete() method.

The @ModelAttribute Annotation

The @ModelAttribute annotation can serve multiple purposes in a Spring MVC application:

  1. Binding Form Parameters to a Bean: When you have a form in your JSP/Thymeleaf page and you want to bind the form fields to a Java object, @ModelAttribute can be used.
  2. Adding Common Attributes to the Model: You can use the @ModelAttribute at the method level to add common attributes that should be populated for multiple request mappings.
  3. Method Argument: When placed before a method parameter, it indicates the argument should be retrieved from the model.

Example of Binding Form Parameters

Imagine you have a registration form on a webpage:

<form action="/register" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Register">
</form>

Here’s how you can bind the form fields to a User object:

@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@ModelAttribute User user) {
// Now user object contains the data from form fields
// Do operations like saving to the database
return "successPage";
}

Example of Adding Common Attributes

@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("message", "Welcome to our website!");
}

Any method annotated with @ModelAttribute (and not having a return value) will be executed before @RequestMapping annotated methods, ensuring attributes added are available in the model for views.

Key Points to Remember:

  • @ModelAttribute methods are invoked before the controller methods annotated with @RequestMapping are executed. This ensures that the model data is set up and readily available.
  • If the name of the model attribute is not specified in the @ModelAttribute annotation, the name of the parameter type (decapitalized) is used by default.

Conclusion

In Spring MVC, both @SessionAttributes and @ModelAttribute offer unique functionalities that make web application development more streamlined. While @SessionAttributes is primarily used for persisting model attributes across multiple sessions, @ModelAttribute provides versatile ways to bind form parameters to beans, add common attributes, and reference model data. Mastery of these annotations, coupled with a good understanding of the broader Spring ecosystem, will equip developers to handle a variety of web development challenges.

  1. Spring Framework Documentation — MVC
  2. Baeldung — Guide to @SessionAttributes
  3. Baeldung — Guide to @ModelAttribute
Spring Boot icon by Icons8

--

--

Alexander Obregon

Software Engineer, fervent coder & writer. Devoted to learning & assisting others. Connect on LinkedIn: https://www.linkedin.com/in/alexander-obregon-97849b229/