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

1

12

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";
}
Murphree answered 10/5, 2014 at 1:25 Comment(0)
S
11

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";
}
Saguache answered 10/5, 2014 at 3:52 Comment(2)
Thank you your comment is more clear.so we are using model attribute to get data from jsp file and to send data to jsp file we are using model with returning modelandview from handler,right?Murphree
You can use ModelAttribute in both cases, as it puts attributes in the request scope so they are available in the jsp context. Keep returning only the view name or redirect as a String is sufficient here.Saguache

© 2022 - 2024 — McMap. All rights reserved.