Spring: @ModelAttribute VS @RequestBody

后端 未结 7 467
闹比i
闹比i 2020-12-04 16:19

Please correct me if I am wrong. Both can be used for Data Binding.

The question is when to use @ModelAttribute?

@RequestMapping(val         


        
相关标签:
7条回答
  • 2020-12-04 16:49

    I think @ModelAttribute and @RequestBody both are having same use, only difference is @ModelAttribute use for normal spring MVC and @RequestBody use for REST web service. It is @PathVariable and @PathParam. But in in both the cases we can mix it. we can use @PathVariable in REST and vice versa.

    0 讨论(0)
  • 2020-12-04 16:51

    You can directly access your "pet" object in view layer, if you use ModelAttribute annotation. Also, you can instantiate this object in a method on your controller to put your model. see this.

    ModelAttribute gives you a chance to use this object partial, but with RequestBody, you get all body of request.

    0 讨论(0)
  • 2020-12-04 16:52

    With @ModelAttribute, you pass data in URL params and with @RequestBody you pass it as JSON body. If you're making a REST API then it's better to use @RequestBody. Over most youtube tutorials you might find use of @ModelAttribute - That's simply because they might be demonstrating concepts regarding Spring MVC and are using URL's to pass data.

    0 讨论(0)
  • 2020-12-04 16:55

    @ModelAttribute is used for binding data from request param (in key value pairs),

    but @RequestBody is used for binding data from whole body of the request like POST,PUT.. request types which contains other format like json, xml.

    0 讨论(0)
  • 2020-12-04 17:07

    The simplest way for my understanding is, the @ModelAttribute will take a query string. so, all the data are being pass to the server through the url.

    As for @RequestBody, all the data will be pass to the server through a full JSON body.

    0 讨论(0)
  • 2020-12-04 17:09

    I find that @RequestBody (also annotating a class as @RestController) is better for AJAX requests where you have complete control over the contents of the request being issued and the contents are sent as either XML or JSON (because of Jackson). This allows the contents to easily create a model object. Conversely, @ModelAttribute seems to be better suited to forms where there is a "command" object backing a form (which may not necessarily be a model object).

    0 讨论(0)
提交回复
热议问题