Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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";
}
like image 336
ssmm Avatar asked May 10 '14 01:05

ssmm


1 Answers

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";
}
like image 152
Patrice Blanchardie Avatar answered Sep 25 '22 17:09

Patrice Blanchardie