Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

learning Spring's @RequestBody and @RequestParam

I'm editing a web project that uses Spring and I need to adding some of Spring's annotations. Two of the ones I'm adding are @RequestBody and @RequestParam. I've been poking around a little and found this, but I still don't completely understand how to use these annotations. Could anyone provide an example?

like image 987
Josh Avatar asked Jul 26 '10 17:07

Josh


People also ask

Can we use @RequestBody and @RequestParam together?

nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

What is the difference between @RequestParam and @RequestBody?

So basically, while @RequestBody maps entire user request (even for POST) to a String variable, @RequestParam does so with one (or more - but it is more complicated) request param to your method argument.

What is difference between @RequestBody and @ModelAttribute?

@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 difference between @RequestBody and @ResponseBody?

By using @RequestBody annotation you will get your values mapped with the model you created in your system for handling any specific call. While by using @ResponseBody you can send anything back to the place from where the request was generated. Both things will be mapped easily without writing any custom parser etc.


1 Answers

Controller example:

@Controller
class FooController {
    @RequestMapping("...")
    void bar(@RequestBody String body, @RequestParam("baz") baz) {
        //method body
    }
}

@RequestBody: variable body will contain the body of the HTTP request

@RequestParam: variable baz will hold the value of request parameter baz

like image 131
Arjan Avatar answered Nov 15 '22 14:11

Arjan