Summary of the use posture of spring's requestbody
There are several different ways to process request parameters in Springmvc, such as our common
HttpServletRequest
Get By Object
@PathVariable
get URL parameters based on annotations
@RequestParam
GET request parameters based on annotations
- Get request parameters based on Bean's method
@ModelAttribute
GET request parameters based on annotations
There are several ways to be interested in this blog post: SPRINGMVC Request Parameter Acquisition method
In addition to the above several ways, there is also a @RequestBody
way to use, this article mainly introduces the use of such communication parameters and related considerations
I. Use posture 1. Service Interface
With the spring framework, there's no difficulty in using it, and @RequestBody
it's easy to write a case to use, as follows
@Slf4j@RestControllerpublic class ReqBodyController { @Data @NoArgsConstructor @AllArgsConstructor public static class Req { private String key; private Integer size; } @RequestMapping(value = "/body", method = {RequestMethod.POST, RequestMethod.GET, RequestMethod.OPTIONS}) public BaseRsp body(@RequestBody Req req) { log.info("req: {}", req); return new BaseRsp<>(req); }}
Look at the above implementation, and our usual wording is no different, nothing @RequsetParam
more than to replace the previous annotations with @RequsetBody
annotations, and this note inside only one filed, RequsetParam
less than
@Target({ElementType.PARAMETER})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface RequestBody { // 默认参数必须存在,否则会抛一个异常 boolean required() default true; }
See the above implementation, it can also be guessed that the note for the backend, write no problem, the key is how to use (specifically, how to use the front end)
2. Interface calls
It's finished, the next point is how to use it, before using it, it is necessary to understand the RequestBody
original and the application scenario of the annotation (in other words, it is different from the Requestparam, why do a separate this thing out)
Requestbody
@requestBody annotations are often used to handle content-type not the default application/x-www-form-urlcoded encoded content, such as: Application/json or application/. XML, and so on. Typically, it is often used to handle application/json types.
A. Content-type definition
Before entering the next step, it is necessary to say the Content-Type
role of the HTTP request header, the following paragraph from other posts, the original link to see the last
MediaType, which is the Internet media type, the Internet medium, or the MIME type, in the HTTP protocol message header, uses Content-type to represent the media type information in the specific request.
Common media formats are as follows:
- text/html:html format
- Text/plain: Plain Text Format
- Text/xml:xml format
- Image/gif:gif Picture Format
- Image/jpeg:jpg Picture Format
- Image/png:png Picture Format
Types of media formats that start with application:
- application/xhtml+xml:xhtml format
- Application/xml:xml data format
- Application/atom+xml:atom XML Aggregation format
- Application/json:json data format
- Application/pdf:pdf format
- Application/msword:word Document Format
- Application/octet-stream: binary stream data (e.g., common file downloads)
- Application/x-www-form-urlencoded:
B. Content-type instance Description
Above is the basic definition and value, the following examples of the typical ways to explain
- Application/x-www-form-urlencoded: Data is encoded as a name/value pair. This is the standard encoding format.
- Multipart/form-data: Data is encoded as a message, and each control on the page corresponds to a part of the message.
- Text/plain: Data is encoded in plain text (text/json/xml/html) with no controls or formatting characters
For front-end use, the Enctype property of form forms is encoded in two common ways: application/x-www-form-urlencoded
and multipart/form-data
, by default application/x-www-form-urlencoded
.
GET request
When a GET request is initiated, the browser uses the application/x-www-form-urlencoded
method to convert the form data into a string (key1=value1&key2=value2 ...) Stitching to the URL, this is the case of our common URL with request parameters
Post form
When initiating a POST request, if the file is not transmitted, the browser is also the result of encapsulating form form data into the k=v of the HTTP body, take the Open source China Blog submitted form For example, a typical post form, upload data assembled in form data, for the KV structure
If there are files in the scene, the Content-type type will be upgraded to multipart/form-data
, this piece is not detailed expansion, after the opportunity to say
Post JSON string
Post form In addition to the previous way, there is also a common, that is, all the form data placed in a large JSON string, and then dropped to the backend, there is also an online instance, an e-commerce platform of the product published, as follows
Note the above request Payload, is a large JSON string, and the front difference is obvious
C. Requestbody Request
According to the definition of requestbody, to access the previously defined interface, using the traditional form delivery method is not possible, the Curl command is tested as follows
curl -X POST -d ‘key=haha&size=123‘ http://127.0.0.1:19533/body
The output of the backend corresponds to the following (an exception is thrown, indicating that the @requestbody annotation decoration Rest interface does not supportContent type ‘application/x-www-form-urlencoded;charset=UTF-8‘
Therefore, the use of posture needs to display the add request header, the transfer parameter also changes
curl -l -H "Content-type: application/json" -X GET -d ‘{"key": "!23", "size": 10}‘ http://127.0.0.1:19533/body
The returned results are as follows
3. Precautions A. Content-type Displays the specified
According to the previous instructions, it is possible to know the @RequestBody
use of this annotation so that the rest interface receives a request that is no longer content-type application/x-www-form-urlencoded
, but instead needs to display the specifiedapplication/json
B. Request method
Does Requestbody support the Get method? The previous use of the post submission parameters, if changed to get what?
Curl Test Mode
curl -l -H "Content-type: application/json" -X GET -d ‘{"key": "!23", "size": 10}‘ http://127.0.0.1:19533/body\?key\=app
Corresponding back-end debug as follows, found using Get method, and no problem, still can get to parameters
To the famous postman to test it.
When using the Post method request, as follows, the main is to modify the header Content-type, and then add the JSON string format request in the body
However, after the change to get, the body is directly grayed out, that is, it does not support the GET request, the body data is submitted
URL Request method
The next step is to change the URL request to see if the GET request is supported directly
http://127.0.0.1:19533/body?{"key": "!23", "size": 10}
In the browser input, server 400, replaced by curl request, throw is missing requestbody exception, that is, the JSON string stitching into the URL seemingly not (also may be my use posture is wrong ...) )
Summary
- To summarize here, when using Requestbody to get parameters, or honestly choose the Post method is appropriate, as for the reason, with the public, with the mainstream, follow the habit of everyone to go better
C. Parameter acquisition
This is mainly the back-end programming interface, get requestbody parameters of the problem, through the test, found in the HttpServletRequest
parameters, actually can't get the submitted requestbody parameters, demonstrated as follows
The request URL is
curl -l -H "Content-type: application/json" -X POST -d ‘{"key": "!23", "size": 10}‘ http://127.0.0.1:19533/body\?url\=ddd
The corresponding debug is as follows, url parameter can get, requestbody parameter not
First of all, the following analysis, did not look at the source code, is purely personal inference, if there is a problem, to be misled by the friend apologized, but also hope to have a better understanding of the friends, a lot of criticism
从传文件的思路出发,前端传文件给后端时,后端是基于流的方式,将上传的二进制流,写入到`MultipartFile`;而二进制流读完之后,没法再重复的读RequestBody可能也是这么个逻辑,首先是从HttpServletRequest的Reader流中读取body参数并封装到上面的req对象,而不会像url参数一样,写回到`javax.servlet.ServletRequest#getParameterMap`
Make a small verification of the above guess, and change it to get the request body parameter directly from the HttpServletRequest reader stream
@RequestMapping(value = "/body", method = {RequestMethod.POST, RequestMethod.GET, RequestMethod.OPTIONS})public BaseRsp body(HttpServletRequest request) throws IOException { BufferedReader reader = request.getReader(); StringBuilder builder = new StringBuilder(); String line = reader.readLine(); while (line != null) { builder.append(line); line = reader.readLine(); } reader.close(); String reqBody = builder.toString(); Req req = JSON.parseObject(reqBody, Req.class); log.info("req: {}, request: {}", req, request.getParameterMap()); return new BaseRsp<>(req);}
Verify the following
In fact, here, there is an interesting place has aroused my curiosity, that is in the spring container httpservletrequest this thing, how it works, there is a chance to talk later, here do not expand ...
4. Summary
- Reuqestbody is primarily a request parameter that handles JSON string format, requiring the user to specify the header
content-type:application/json
- Requestbody typically requires the caller to use a POST request
- The Requsetbody parameter is not placed in the HttpServletRequest map, so it cannot be
javax.servlet.ServletRequest#getParameter
obtained by
Ii. other 0. Reference
- How to get the request parameter of SPRINGMVC
- An explanation of Content-type in HTTP
1. A grey ash Blog:https://liuyueyi.github.io/hexblog
A gray and gray personal blog, recording all the study and work in the blog, welcome everyone to visit
2. Disclaimer
The letter is not as good as, has been on the content, purely opinion, because of limited personal ability, inevitably there are omissions and errors, such as the detection of bugs or better suggestions, welcome criticism, please feel grateful
- Weibo address: small Gray Gray Blog
- QQ: A grey/grey/3302797840
3. Scan for attention
Small grey ash blog& public number
Knowledge Planet
Summary of the use posture of 180730-spring requestbody