learning Spring's @RequestBody and @RequestParam

后端 未结 2 1303
暖寄归人
暖寄归人 2020-12-13 11:21

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 p

相关标签:
2条回答
  • 2020-12-13 11:28

    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

    0 讨论(0)
  • 2020-12-13 11:36

    @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 讨论(0)
提交回复
热议问题