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
What is difference between @RequestBody and @RequestParam?
提问by Manoj Singh
I have gone through the Spring documentation to know about @RequestBody
, and they have given the following explanation:
我已经通过 Spring 文档了解了@RequestBody
,他们给出了以下解释:
The
@RequestBody
method 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
.HttpMessageConverter
is responsible for converting from the HTTP request message to an object and converting from an object to the HTTP response body.
DispatcherServlet
supports annotation based processing using theDefaultAnnotationHandlerMapping
andAnnotationMethodHandlerAdapter
. In Spring 3.0 theAnnotationMethodHandlerAdapter
is extended to support the@RequestBody
and has the followingHttpMessageConverter
s registered by default:...
您可以使用 将请求正文转换为方法参数
HttpMessageConverter
。HttpMessageConverter
负责将 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 @RequestParam
definition in spring doc is
@RequestParam
spring 文档中的定义是
Annotation which indicates that a method parameter should be bound to a web request parameter. Supported for annotated handler methods in
Servlet
andPortlet
environments.
指示方法参数应绑定到 Web 请求参数的注释。支持
Servlet
和Portlet
环境中带注释的处理程序方法。
I have become confused between them. Please, help me with an example on how they are different from each other.
我在他们之间感到困惑。请帮我举一个例子,说明它们之间的区别。
回答by Patrik Bego
@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.
@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) {...
@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.
@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
@RequestParam
makes 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 请求
@RequestBody
makes 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 JSON
data as such coming from the front end and hits your controller class
您有JSON
来自前端的数据并点击您的控制器类
{
"city": "Sydney",
"country": "Australia"
}
Java
Code - 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.
@RequestParam
annotation 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 @RequestBody
maps entire user request (even for POST) to a String variable, @RequestParam
does 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
,处理请求正文。
@RequestParam
←application/x-www-form-urlencoded
,@RequestBody
←application/json
,@RequestPart
←multipart/form-data
,
@RequestParam
←application/x-www-form-urlencoded
,@RequestBody
←application/json
,@RequestPart
←multipart/form-data
,
RequestParam (Spring Framework 5.1.9.RELEASE API)
map to query parameters, form data, and parts in multipart requests.
RequestParam
is likely to be used with name-value form fieldsRequestBody (Spring Framework 5.1.9.RELEASE API)
bound to the body of the web request. The body of the request is passed through an HttpMessageConverterto resolve the method argument depending on the
content type
of the request. (e.g. JSON, XML)RequestPart (Spring Framework 5.1.9.RELEASE API)
used to associate the part of a "
multipart/form-data
" requestRequestPart
is likely to be used with parts containing more complex contentHttpMessageConverter (Spring Framework 5.1.9.RELEASE API)
a converter that can convert from and to HTTP requests and responses.
All Known Implementing Classes: ..., AbstractJsonHttpMessageConverter, AbstractXmlHttpMessageConverter, ...
RequestParam(Spring 框架 5.1.9.RELEASE API)
映射到查询参数、表单数据和多部分请求中的部分。
RequestParam
可能与名称-值表单字段一起使用RequestBody(Spring 框架 5.1.9.RELEASE API)
绑定到 Web 请求的正文。请求的正文通过HttpMessageConverter传递,以根据请求的内容解析方法参数
content type
。(例如 JSON、XML)RequestPart (Spring Framework 5.1.9.RELEASE API)
用于关联“
multipart/form-data
”请求的部分RequestPart
可能与包含更复杂内容的部分一起使用HttpMessageConverter(Spring 框架 5.1.9.RELEASE API)
一个转换器,可以在 HTTP 请求和响应之间进行转换。
所有已知的实现类: ..., AbstractJsonHttpMessageConverter, AbstractXmlHttpMessageConverter, ...