Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: @ModelAttribute VS @RequestBody

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!!

like image 808
Touchstone Avatar asked Feb 17 '14 08:02

Touchstone


People also ask

What is the difference between @ModelAttribute and RequestBody?

@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.

What is @ModelAttribute used for?

@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.

What is @RequestBody in spring?

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.

What is the difference between @RequestParam and @ModelAttribute?

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.


1 Answers

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.

like image 82
CharlesC Avatar answered Sep 19 '22 13:09

CharlesC