开发者

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 a开发者_JAVA技巧dding 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?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜