简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM