What is the role of the @ModelAttribute annotation?

@ModelAttribute serves two related purposes in Spring MVC: binding submitted form data onto a Java object as a method parameter, and adding data to the model so it's available to a view or across multiple handler methods.

Key Points: • As a method parameter annotation, it binds matching request parameters onto the properties of the given object, useful for both pre-filling and processing forms. • As a method annotation (with no return going directly to the view), it adds the return value to the model under a given attribute name for every request handled by that controller. • It works closely with @Valid and BindingResult to combine binding with validation in one step. • It supports pre-populating a form with existing data, such as loading an entity by ID before rendering an edit form. • Using it for shared reference data (like dropdown options) keeps that logic in one place instead of repeating it in every handler method.

Example: An edit-profile form uses @ModelAttribute to both load the current user's data into the form on GET and bind the submitted changes back onto a User object on POST, keeping the binding logic consistent in both directions.

Code Example:

@ModelAttribute("user")
public User populateUser(@RequestParam Long id) {
    return userService.findById(id);
}

Interview Tip: A concise interview answer is:

"@ModelAttribute binds request data onto a Java object for form submissions, and when used on its own method it adds shared data to the model for every request handled by that controller. It's what makes pre-populating an edit form and processing its submission use the same binding mechanism."