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?
-
3There are good examples in the documentation, for both [`@RequestMapping`](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestparam) and [`@RequestBody`](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestbody) – skaffman Jul 26 '10 at 17:41
2 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

- 33,636
- 11
- 99
- 120

- 19,957
- 2
- 55
- 48
-
-
10No it cannot, there is only one HTTP Body, so there can only be one RequestBody variable – lanoxx May 23 '13 at 21:59
@RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.
For example Angular request for Spring RequestParam(s) would look like that:
$http.post('http://localhost:7777/scan/l/register', {params: {"username": $scope.username, "password": $scope.password, "auth": true}}).
success(function (data, status, headers, config) {
...
})
@RequestMapping(method = RequestMethod.POST, produces = "application/json", value = "/register")
public Map<String, String> register(Model uiModel,
@RequestParam String username, @RequestParam String password, boolean auth,
HttpServletRequest httpServletRequest) {...
@RequestBody annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters. This annotation indicates a method parameter should be bound to the body of the web request.
For example Angular request for Spring RequestBody would look like that:
$scope.user = {
username: "foo",
auth: true,
password: "bar"
};
$http.post('http://localhost:7777/scan/l/register', $scope.user).
success(function (data, status, headers, config) {
...
})
@RequestMapping(method = RequestMethod.POST, produces = "application/json", value = "/register")
public Map<String, String> register(Model uiModel,
@RequestBody User user,
HttpServletRequest httpServletRequest) {...
Hope this helps.

- 4,009
- 1
- 26
- 24