Please correct me if I am wrong. Both can be used for Data Binding.
The question is when to use @ModelAttribute?
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST) public String processSubmit(@ModelAttribute Pet pet) { }
In addition, when to use @RequestBody?
@RequestMapping(value = "/user/savecontact", method = RequestMethod.POST public String saveContact(@RequestBody Contact contact){ }
According to my understanding both serves the similar purpose.
Thanks!!
@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.
@ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute, and then exposes it to a web view.
The @RequestBody annotation allows us to retrieve the request's body. We can then return it as a String or deserialize it into a Plain Old Java Object (POJO). Spring has built-in mechanisms for deserializing JSON and XML objects into POJOs, which makes this task a lot easier as well.
In general, @RequestParam is best for reading a small number of params. @ModelAttribute is used when you have a form with a large number of fields.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With