Spring Boot @ModelAttribute Example

1. Introduction

The @ModelAttribute annotation in Spring Boot is commonly used in MVC applications to bind HTTP request parameters to Java objects and to populate model attributes for a view. It is a flexible tool that facilitates data flow between the web layer and the service layer.

Key Points:

1. @ModelAttribute can be used on method parameters to bind incoming data to a model attribute.

2. It can also be used on methods to add attributes to the model before any @RequestMapping method is invoked.

3. This annotation binds request parameters to an object, and it can also be used to populate model attributes for views.

2. Implementation Steps

1. Create a Spring Boot application with the necessary web dependencies.

2. Define a model class that represents the form data you wish to bind.

3. Create a controller with methods annotated with @ModelAttribute to bind request parameters or to populate the model.

4. Implement a view template to display the model data.

5. Run the application and submit data through a form to see the model binding in action.

3. Implementation Example

Here is the complete code that demonstrates the usage of @ModelAttribute annotation:
// Step 2: Define a model class
class UserForm {
    private String username;
    private String email;
    // Getters and setters are omitted for brevity
}

// Step 3: Create a controller with model attributes
@Controller
public class RegistrationController {

    // Step 3.1: Add a global model attribute for all model maps
    @ModelAttribute("attributeName")
    public String globalAttribute() {
        return "This is a global attribute";
    }

    // Step 3.2: A handler method with @ModelAttribute to bind form data
    @PostMapping("/register")
    public String registerUser(@ModelAttribute UserForm userForm, Model model) {
        // A real application would save the user details here
        model.addAttribute("user", userForm);
        return "userView";
    }
}

// Step 4: Implement the Thymeleaf view template
// File: src/main/resources/templates/userView.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Registration</title>
</head>
<body>
    <h1>Registration Details</h1>
    <p>Username: <span th:text="${user.username}">Username</span></p>
    <p>Email: <span th:text="${user.email}">Email</span></p>
    <p th:text="${attributeName}">Global Attribute</p>
</body>
</html>

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

Output:

After submitting the registration form you should see the following:
Registration Details
Username: JohnDoe
Email: john.doe@example.com
This is a global attribute

Explanation:

1. UserForm is a simple Java class with username and email fields that correspond to the form inputs.

2. RegistrationController is a @Controller in Spring MVC which will handle registration form submissions.

3. The method globalAttribute annotated with @ModelAttribute adds an attribute to every model in the controller.

4. The registerUser method handles the form submission, binding form data to the UserForm object.

5. userView.html is a Thymeleaf template file that will display the bound user data and the global attribute.

6. ModelAttributeExampleApplication contains the main method and is the entry point of the Spring Boot application.

7. The output is a web page rendered by userView.html, displaying the user's submitted details and a global attribute that was added to all model maps within the controller.


Comments