How does the @ModelAttribute annotation work in Spring MVC?

How does the @ModelAttribute annotation work in Spring MVC?

A) It binds a model attribute to a method parameter
B) It maps HTTP request parameters to method arguments
C) It defines a model attribute for data binding
D) Both A and C

Answer:

D) Both A and C

Explanation:

The @ModelAttribute annotation in Spring MVC serves two main purposes: it binds a model attribute to a method parameter and defines a model attribute for data binding. This annotation can be used on method parameters as well as on methods within a controller.

For example:


@Controller
public class MyController {

    @ModelAttribute("user")
    public User addUserToModel() {
        return new User();
    }

    @PostMapping("/register")
    public String register(@ModelAttribute("user") User user) {
        // Registration logic here
        return "registrationSuccess";
    }
}

In this example, the @ModelAttribute("user") annotation on the addUserToModel() method adds a User object to the model, making it available for data binding in the view. The @ModelAttribute("user") annotation on the user parameter in the register method binds the incoming form data to the User object.

Using @ModelAttribute helps simplify data binding in Spring MVC by allowing you to automatically populate model attributes and handle form submissions with ease.

Reference links:

Spring Boot Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top