小编典典

@RequestBody和@RequestParam有什么区别?

spring

我遍历了Spring文档以了解@RequestBody,他们给出了以下解释:

所述@RequestBody方法参数注释指示方法参数应绑定到HTTP请求正文的值。例如:

@RequestMapping(value = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
  writer.write(body);
}

你可以通过使用将请求主体转换为方法参数HttpMessageConverterHttpMessageConverter负责从HTTP请求消息转换为对象,并从对象转换为HTTP响应主体。

DispatcherServlet支持使用DefaultAnnotationHandlerMapping和进行基于注释的处理AnnotationMethodHandlerAdapter。在Spring 3.0中,AnnotationMethodHandlerAdapter扩展为支持,@RequestBody并且HttpMessageConverter默认情况下注册了以下:

但我的困惑是他们在文档中写的句子是

@RequestBody方法参数注释指示方法参数应绑定到HTTP请求正文的值。

那是什么意思?谁能给我一个例子吗?

@RequestParamspring doc中的定义是

指示方法参数应绑定到Web请求参数的注释。在ServletPortlet环境中支持带注释的处理程序方法。

我对他们感到困惑。请帮我举个例子,说明它们之间的区别。


阅读 2716

收藏
2020-04-12

共1个答案

小编典典

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

例如,对Spring RequestParam(s)的角度请求如下所示:

$http.post('http://localhost:7777/scan/l/register?username="Johny"&password="123123"&auth=true')
      .success(function (data, status, headers, config) {
                        ...
                    })

带有RequestParam的端点:

@RequestMapping(method = RequestMethod.POST, value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestParam String username,
                                    @RequestParam String password,
                                    @RequestParam 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) {
                            ...
                        })

带有RequestBody的端点:

@RequestMapping(method = RequestMethod.POST, produces = "application/json", 
                value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestBody User user,
                                    HttpServletRequest httpServletRequest) {... 

希望这可以帮助。

2020-04-12