spring @RequestBody 和 @RequestParam 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28039709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:18:53  来源:igfitidea点击:

What is difference between @RequestBody and @RequestParam?

springspring-mvcspring-bootservlet-3.0http-request-parameters

提问by Manoj Singh

I have gone through the Spring documentation to know about @RequestBody, and they have given the following explanation:

我已经通过 Spring 文档了解了@RequestBody,他们给出了以下解释:

The @RequestBodymethod parameter annotation indicates that a method parameter should be bound to the value of the HTTP request body. For example:

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

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

You convert the request body to the method argument by using an HttpMessageConverter. HttpMessageConverteris responsible for converting from the HTTP request message to an object and converting from an object to the HTTP response body.

DispatcherServletsupports annotation based processing using the DefaultAnnotationHandlerMappingand AnnotationMethodHandlerAdapter. In Spring 3.0 the AnnotationMethodHandlerAdapteris extended to support the @RequestBodyand has the following HttpMessageConverters registered by default:

...

您可以使用 将请求正文转换为方法参数HttpMessageConverterHttpMessageConverter负责将 HTTP 请求消息转换为对象,以及将对象转换为 HTTP 响应体。

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

...

but my confusion is the sentence they have written in the doc that is

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

The @RequestBody method parameter annotation indicates that a method parameter should be bound to the value of the HTTP request body.

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

What do they mean by that? Can anyone provide me an example?

他们这是什么意思?谁能给我一个例子?

The @RequestParamdefinition in spring doc is

@RequestParamspring 文档中的定义是

Annotation which indicates that a method parameter should be bound to a web request parameter. Supported for annotated handler methods in Servletand Portletenvironments.

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

I have become confused between them. Please, help me with an example on how they are different from each other.

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

回答by Patrik Bego

@RequestParamannotated 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.

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

For example Angular request for Spring RequestParam(s) would look like that:

例如,Spring RequestParam(s) 的 Angular 请求将如下所示:

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

Endpoint with RequestParam:

带有 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) {...

@RequestBodyannotated 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.

@RequestBody带注释的参数链接到 HTTP 请求正文。使用 HttpMessageConverters 将参数值转换为声明的方法参数类型。该注解表示方法参数应该绑定到 Web 请求的正文。

For example Angular request for Spring RequestBody would look like that:

例如,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) {
                            ...
                        })

Endpoint with RequestBody:

带有 RequestBody 的端点:

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

Hope this helps.

希望这可以帮助。

回答by Dulith De Costa

@RequestParammakes Spring to map request parameters from the GET/POST request to your method argument.

@RequestParam使 Spring 将请求参数从 GET/POST 请求映射到您的方法参数。

GET Request

获取请求

http://testwebaddress.com/getInformation.do?city=Sydney&country=Australia

public String getCountryFactors(@RequestParam(value = "city") String city, 
                    @RequestParam(value = "country") String country){ }

POST Request

POST 请求

@RequestBodymakes Spring to map entire request to a model class and from there you can retrieve or set values from its getter and setter methods. Check below.

@RequestBody使 Spring 将整个请求映射到模型类,然后您可以从其 getter 和 setter 方法中检索或设置值。检查下面。

http://testwebaddress.com/getInformation.do

You have JSONdata as such coming from the front end and hits your controller class

您有JSON来自前端的数据并点击您的控制器类

{
   "city": "Sydney",
   "country": "Australia"
}

JavaCode - backend (@RequestBody)

Java代码 - 后端 ( @RequestBody)

public String getCountryFactors(@RequestBody Country countryFacts)
    {
        countryFacts.getCity();
        countryFacts.getCountry();
    }


public class Country {

    private String city;
    private String country;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

回答by Rafal G.

@RequestParamannotation tells Spring that it should map a request parameter from the GET/POST request to your method argument. For example:

@RequestParam注释告诉 Spring 它应该将请求参数从 GET/POST 请求映射到您的方法参数。例如:

request:

要求:

GET: http://someserver.org/path?name=John&surname=Smith

endpoint code:

端点代码:

public User getUser(@RequestParam(value = "name") String name, 
                    @RequestParam(value = "surname") String surname){ 
    ...  
    }

So basically, while @RequestBodymaps entire user request (even for POST) to a String variable, @RequestParamdoes so with one (or more - but it is more complicated) request param to your method argument.

所以基本上,虽然@RequestBody将整个用户请求(即使是 POST)映射到一个 String 变量,@RequestParam但使用一个(或多个 - 但它更复杂)请求参数到您的方法参数。

回答by Pinkk Wormm

Here is an example with @RequestBody, First look at the controller !!

这是@RequestBody 的例子,首先看控制器!!

  public ResponseEntity<Void> postNewProductDto(@RequestBody NewProductDto newProductDto) {

   ...
        productService.registerProductDto(newProductDto);
        return new ResponseEntity<>(HttpStatus.CREATED);
   ....

}

And here is angular controller

这是角度控制器

function postNewProductDto() {
                var url = "/admin/products/newItem";
                $http.post(url, vm.newProductDto).then(function () {
                            //other things go here...
                            vm.newProductMessage = "Product successful registered";
                        }
                        ,
                        function (errResponse) {
                            //handling errors ....
                        }
                );
            }

And a short look at form

简单看一下表格

 <label>Name: </label>
 <input ng-model="vm.newProductDto.name" />

<label>Price </label> 
 <input ng-model="vm.newProductDto.price"/>

 <label>Quantity </label>
  <input ng-model="vm.newProductDto.quantity"/>

 <label>Image </label>
 <input ng-model="vm.newProductDto.photo"/>

 <Button ng-click="vm.postNewProductDto()" >Insert Item</Button>

 <label > {{vm.newProductMessage}} </label>

回答by Ch. Rohit Malik

It is very simple just look at their names @RequestParam it consist of two parts one is "Request" which means it is going to deal with request and other part is "Param" which itself makes sense it is going to map only the parameters of requests to java objects. Same is the case with @RequestBody it is going to deal with the data that has been arrived with request like if client has send json object or xml with request at that time @requestbody must be used.

很简单,看看他们的名字@RequestParam 它由两部分组成,一个是“Request”,这意味着它将处理请求,另一部分是“Param”,它本身是有意义的,它只映射参数对 java 对象的请求。与@RequestBody 的情况相同,它将处理随请求一起到达的数据,就像客户端在那时发送了带有请求的 json 对象或 xml 一样,必须使用 @requestbody。

回答by u5819157

map HTTP request header Content-Type, handle request body.

映射 HTTP 请求头Content-Type,处理请求正文。

  • @RequestParamapplication/x-www-form-urlencoded,

  • @RequestBodyapplication/json,

  • @RequestPartmultipart/form-data,

  • @RequestParamapplication/x-www-form-urlencoded,

  • @RequestBodyapplication/json,

  • @RequestPartmultipart/form-data,