What is the difference between @ModelAttribute, model.addAttribute in spring?

10,767

When used on an argument, @ModelAttribute behaves as follows:

An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, the argument’s fields should be populated from all request parameters that have matching names. This is known as data binding in Spring MVC, a very useful mechanism that saves you from having to parse each form field individually. http://docs.spring.io/spring/docs/4.1.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#mvc-ann-modelattrib-method-args

That's a very powerful feature. In your example, the User object is populated from the POST request automatically by Spring.

The first method, however, simply creates an instance of Userand adds it to the Model. It could be written like that to benefit from @ModelAttribute:

@RequestMapping(method = RequestMethod.GET)
public String setupForm(@ModelAttribute User user) {
    // user.set...
    return "editUser";
}
Share:
10,767
ssmm
Author by

ssmm

Updated on June 21, 2022

Comments

  • ssmm
    ssmm almost 2 years

    i am new Spring learner.i'm really confused about what is the difference between two concept:

    1. @ModelAttribute
    2. model.addAttribute

    in below there are two "user" value.Are these same thing?Why should I use like this? Thank you all

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(ModelMap model) {
        model.addAttribute("user", new User());
        return "editUser";
    }
    
    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit( @ModelAttribute("user") User user, BindingResult result, SessionStatus status) {
        userStorageDao.save(user);
        status.setComplete();
        return "redirect:users.htm";
    }