【问题标题】:learning Spring's @RequestBody and @RequestParam学习 Spring 的 @RequestBody 和 @RequestParam
【发布时间】:2011-03-21 05:21:33
【问题描述】:

我正在编辑一个使用 Spring 的 Web 项目,我需要添加一些 Spring 的注释。我要添加的两个是@RequestBody@RequestParam。我一直在摸索,发现this,但我仍然不完全了解如何使用这些注释。谁能举个例子?

【问题讨论】:

标签: java spring spring-mvc


【解决方案1】:

控制器示例:

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

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

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

【讨论】:

  • 一个方法可以有多个@RequestBody 参数吗?
  • 不行,HTTP Body只有一个,所以RequestBody变量只能有一个
【解决方案2】:

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

例如,对 Spring RequestParam(s) 的 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) {...

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    相关资源
    最近更新 更多