In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to use @ RequestBody. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Disclaimer: a demo based on SpringBoot.
Introduction to the basics:
@ RequestBody is mainly used to receive the data (data in the request body) in the json string passed by the frontend to the backend; GET method has no request body, so when using @ RequestBody to receive data, the frontend cannot submit data in GET mode, but in POST mode. In the same receiving method at the back end, @ RequestBody and @ RequestParam () can be used at the same time, @ RequestBody can have at most one, and @ RequestParam () can have multiple.
Note: one request, only one RequestBody;, one request, can have multiple RequestParam.
Note: when @ RequestParam () and @ RequestBody are used at the same time, the parameters specified by @ RequestParam () can be ordinary elements, arrays, collections, objects, etc. (that is, when @ RequestBody and @ RequestParam () can be used at the same time, the mechanism of the original SpringMVC receiving parameters remains the same, except that RequestBody receives the data in the request body. RequestParam receives parameters in key-value, so it is processed by sections so that it can be received with normal elements, arrays, collections, objects, etc.). That is, if the parameter is placed in the request body and passed into the backend, the backend needs to use @ RequestBody to receive it; if it is not placed in the request body, the backend will use @ RequestParam to receive the parameters sent by the foreground, or the formal parameter can be received without writing anything.
Note: if @ RequestParam (xxx) is written before the parameter, then the front end must have a corresponding xxx name (whether it has a value or not, of course, you can adjust whether it must be passed by setting the required attribute of the annotation). If there is no xxx name, the request will make an error.
Note: if @ RequestParam (xxx) is not written in front of the parameter, the front end may not have a corresponding xxx name. If there is a xxx name, it will match automatically. If not, the request can be sent correctly. Note: this is different from when feign consumes services; when feign consumes services, if nothing is written before the parameters, it will be @ RequestBody by default.
If the backend parameter is an object and is preceded by @ RequestBody, the following requirements must be met when the json parameter is passed by the frontend:
When the class corresponding to the backend @ RequestBody annotation assembles the input stream of HTTP (including the request body) to the target class (that is, the class following @ RequestBody), it will match the attributes of the corresponding entity class according to the key in the json string. If the matching is consistent and the corresponding value of the key in json matches (or can be converted to), I will analyze this item in detail below, and the rest can be simply skipped. But the core logic code at the end of this article and several conclusions must be read! When the type of the corresponding attribute of the entity class is required, the setter method of the entity class is called to assign the value to the property.
In the json string, if value is "", if the backend corresponding attribute is of type String, then you will receive "". If the type of backend attribute is Integer, Double, etc., then you will receive null.
In the json string, if value is null, the null is received at the backend.
If a parameter does not have value, when passing the json string to the backend, either the field is not written into the json string at all, or when writing value, it must have a value, either null or "". Never write something like "stature":, such as:
Note: the use of @ RequestParam () will not be explained one by one here, but can be found in the relevant chapter of "programmer's growth Notes (1)".
The example details:
First give two entity classes to be used later.
User entity class:
Team entity class:
@ RequestBody receives the json data sent by the front end directly through String:
Controller corresponding to the backend:
Use PostMan to test:
@ RequestBody receives the json data sent by the front end as a simple object:
Controller corresponding to the backend:
Use PostMan to test:
@ RequestBody receives json data from the front end as a complex object:
Controller corresponding to the backend:
Use PostMan to test:
@ RequestBody is used with the simple @ RequestParam ():
Controller corresponding to the backend:
Use PostMan to test:
@ RequestBody is used with the complex @ RequestParam ():
Controller corresponding to the backend:
Use PostMan to test:
@ RequestBody receives the json data in the request body; receives the data in the URL without annotation and assembles it into an object:
Controller corresponding to the backend:
Use PostMan to test:
Note: if @ RequestParam () is specified before the parameter of the backend method, the frontend must have a corresponding field (of course, you can adjust whether it must be passed by setting the required attribute of the note), otherwise an error will be reported. If there is no such comment before the parameter, the frontend can or may not be passed, such as:
In the figure above, if token is not specified in the passed parameter, the request can go in normally, but token is null;. If @ RequestParam ("token") is specified before the String token, then the request can enter normally only if the token key is present in the frontend. Otherwise, 400 error will be reported.
The matching rules between @ RequestBody and the json data sent from the front end
Disclaimer: according to different Content-Type and other situations, Spring-MVC will adopt different HttpMessageConverter implementations for information transformation and parsing. The following is the most commonly used: the front end uses Content-Type as the application/json to pass json string data, and the back end receives the data in the @ RequestBody model.
General overview of the process of parsing json data: Http transmits the request body information, which will eventually be encapsulated in com.fasterxml.jackson.core.json.UTF8StreamJsonParser (hint: Spring uses CharacterEncodingFilter to set the default code to UTF-8), and then parses it in public class BeanDeserializer extends BeanDeserializerBase implements java.io.Serializable through the public Object deserializeFromObject (JsonParser p, DeserializationContext ctxt) throws IOException method.
Example of core logic analysis:
Suppose the json string passed by the front end is as follows: {"name1": "Deng Sullivan", "age": 123," mot ":" I am a little bird ~ "} the backend model has only name and age attributes and the corresponding setter/getter method. The core logic of the commonly used deserializeFromObject (JsonParser p, DeserializationContext ctxt) method is given:
Tips: what key do the attributes in the model correspond to?
Here is a brief introduction, more reference:
Public class BeanPropertyMap implements Iterable,java.io.Serializable
Give the test classes in Controller:
Give the attributes in the model (the setter/getter method is not truncated):
Test it with postman, for example:
The above picture is a simple test, but the test is not comprehensive, so we will not take you to test it here, just give it.
A comprehensive conclusion:
Conclusion the annotation ①: @ JsonAlias realizes: when json is converted to model, the specific key in json can be transformed into specific model attributes; however, when the model is converted to json, the corresponding transformed key is still the same as the attribute name, see: request and response of the name field in the example above. The following figure further illustrates:
At this point, when a json string is converted to a model, any key in json that is Name or name123 or name can be recognized.
Conclusion the annotation ②: @ JsonProperty realizes: when json is converted to model, the specific key in json can be transformed into specified model attributes; similarly, when the model is converted to json, the corresponding transformed key is the specified key, see: request and response of the motto field in the example.
The following figure further illustrates:
At this point, when a json string is converted into a model, key is recognized by MOTTO, but key is not recognized by motto.
Conclusion the ③: @ JsonAlias annotation needs to depend on setter and getter, while the @ JsonProperty annotation does not.
Conclusion ④: without considering the above two annotations, key is case-sensitive by default when matching attributes.
Conclusion ⑤: there are multiple json strings of the same key, when converted to the model, the value of the last key in the same key will be copied to the model attribute, because the setter will overwrite the original value. See the gender property in the example.
Conclusion ⑥: when the class corresponding to the backend @ RequestBody annotation assembles the input stream of HTTP (including the request body) to the target class (that is, the class following @ RequestBody), it will match the attributes of the corresponding entity class according to the key in the json string. If the matching is consistent and the corresponding value of the key in json meets (or can be converted to) the type requirements of the corresponding attribute of the entity class, the setter method of the entity class will be called to assign the value to the attribute.
Code managed link: https://github.com/JustryDeng/PublicRepository/tree/master/Abc_RequestBodyAndRequestParam
This is the end of the article on "how to use @ RequestBody". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.