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

ssmm picture ssmm · May 10, 2014 · Viewed 10.1k times · Source

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";
}

Answer

Patrice Blanchardie picture Patrice Blanchardie · May 10, 2014

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";
}