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

I'm the new Spring learner.i'm really confused what is the difference between two concepts:

  • @ModelAttribute
  • model.addAttribute

There are two user values โ€‹โ€‹below. What it is? Why should I use this? Thanks to everyone.

@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"; } 
+6
source share
1 answer

When using the argument, @ModelAttribute behaves as follows:

An @ModelAttribute in the method argument indicates that the argument should be retrieved from the model. If not in the model, the argument must first be created and then added to the model. After being present in the model, the argument fields should be filled out from all query parameters with the corresponding names. This is known as data binding in Spring MVC, a very useful mechanism that eliminates the need to parse each form field separately. http://docs.spring.io/spring/docs/4.1.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#mvc-ann-modelattrib-method-args

This is a very powerful feature. In your example, the User object is populated from the POST request automatically using Spring.

The first method, however, simply creates an instance of User and adds it to the Model. This could be written to take advantage of @ModelAttribute:

 @RequestMapping(method = RequestMethod.GET) public String setupForm(@ModelAttribute User user) { // user.set... return "editUser"; } 
+6
source

All Articles