学习Spring的@RequestBody和@RequestParam注解

问题描述 投票:0回答:2

我正在编辑一个使用 Spring 的 Web 项目,我需要添加一些 Spring 的注释。我添加的两个是

@RequestBody
@RequestParam
。我查了一下,发现了this,但我仍然不完全理解如何使用这些注释。

谁能举个例子吗?

java spring spring-mvc
2个回答
18
投票

控制器示例:

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

@RequestBody变量body将包含HTTP请求的正文

@RequestParam:变量baz将保存请求参数baz的值


3
投票

@RequestParam 带注释的参数链接到特定的 Servlet 请求参数。参数值将转换为声明的方法参数类型。 该注释表示方法参数应绑定到 Web 请求参数。

例如,Spring RequestParam 的 Angular 请求如下所示:

$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 带注释的参数链接到 HTTP 请求正文。使用 HttpMessageConverters 将参数值转换为声明的方法参数类型。 此注释指示方法参数应绑定到 Web 请求的正文。

例如,Spring RequestBody 的 Angular 请求如下所示:

$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) {...

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.