当前位置:网站首页>@Requestbody annotation

@Requestbody annotation

2022-06-24 11:05:00 GuochaoHN

Tips : It is suggested that we must look at the following @RequestBody And six important conclusions ! The first half of this article is all about some basics
            General knowledge , Optional skip .

Statement : This paper is based on SpringBoot, A demonstration of .


Introduction to basic knowledge :

        @RequestBody Mainly used to receive the front end to the back end json character string Of the data in ( Of the data in the request body ); The most common way to use the request body to pass parameters is undoubtedly POST Request the , So use @RequestBody When receiving data , Commonly used POST Way to submit . In the same receiving method at the back end ,@RequestBody And @RequestParam() Can be used at the same time ,@RequestBody There can be at most one , and @RequestParam() There can be multiple .

notes : A request , only one RequestBody; A request , There can be multiple RequestParam.

notes : When used at the same time @RequestParam() and @RequestBody when ,@RequestParam() The specified parameter can be a normal element 、
        Array 、 aggregate 、 Objects, etc. ( namely : When ,@RequestBody And @RequestParam() When it can be used at the same time , primary SpringMVC receive
        The mechanism of the parameter does not change , It's just RequestBody What we receive is the data in the request body ; and RequestParam Receive is key-value
        The parameters inside , So it's going to be faceted so that you can use ordinary elements 、 Array 、 aggregate 、 Object, etc ).
        namely : If the parameter is placed in the request body ,application/json Words coming into the backstage , So the backstage needs to use @RequestBody To receive ;
              If it's not in the request body , So when the background receives the parameters from the foreground , Use @RequestParam To receive , or
              Before the formal parameter You can receive nothing without writing .

notes : If the parameter is written before @RequestParam(xxx), Then the front end must have a corresponding xxx Only by name ( Whether it's worth it or not , Of course
        Set the required Property to adjust whether it is necessary to transmit ), without xxx Famous words , Then the request will go wrong , newspaper 400.

notes : If the parameter is not written before @RequestParam(xxx) Words , Then the front end can have no corresponding xxx Only by name , If there is xxx name
        Words , Then it will automatically match ; If not , The request can also be sent correctly .
        Retrospection : Here with feign Different consumer services ;feign When consuming Services , If nothing is written before the parameter , Then it will be defaulted to be
                  @RequestBody Of .

If the backend parameter is an object , And this parameter is preceded by @RequestBody Embellished , So front end delivery json When parameters are , The following requirements must be met :

  • Back end @RequestBody The class corresponding to the annotation will HTTP The input stream of ( With requester ) Assemble to target class ( namely :@RequestBody The following class ) when , Will be based on json In the string key To match the properties of the corresponding entity class , If the match is consistent and json It's time to key The corresponding value corresponds to ( Or it can be converted to ), This one I will analyze in detail below , Others can be simply omitted , however The core logic code and several conclusions at the end of this article must be based on !  When the type of the corresponding property of the entity class requires , Will call entity class setter Method to assign a value to the property .

  • json In a string , If value by "" Words , If the backend corresponding property is String Type of , So what I received was "", If it is the type of back-end property, it is Integer、Double Other types , So what you receive is null.

  • json In a string , If value by null Words , What the backend receives is null.

  • If a parameter doesn't have value Words , Passing on json String to back end , Or just don't write this field to json In a string ; Or write value when ,  It must be worth ,null  or "" Will do . There must be no such thing "stature":, This way of writing , Such as :

notes : About @RequestParam() Usage of , I will not explain it here , See 《 Programmer growth notes ( One )》 Related chapters in .


Example details :

First, we give two entity classes to be used later

User Entity class :

Team Entity class :

@RequestBody Directly to String Receive from the front end json data :

The back end corresponds to Controller:

Use PostMan test :

@RequestBody Receive the data from the front end as a simple object json data :

The back end corresponds to Controller:

Use PostMan test :

@RequestBody Receive the front-end transmission with complex objects json data :

The back end corresponds to Controller:

Use PostMan test :

@RequestBody With simple @RequestParam() Use at the same time :

The back end corresponds to Controller:

Use PostMan test :

@RequestBody And complicated @RequestParam() Use at the same time :

The back end corresponds to Controller:

Use PostMan test :

@RequestBody Receive... In the body of the request json data ; Receive without comment URL And assemble the data into objects :

The back end corresponds to Controller:

Use PostMan test :

notes : If before the backend method parameter , It specifies @RequestParam() Words , Then the front end must have corresponding fields ( Of course, by setting
        It should be noted that required Property to adjust whether it is necessary to transmit ), No will report an error ; If there is no comment before the parameter , Then the front end can transmit , Can also be
        With no transmission , Such as :

Above picture , If we don't specify token, Then ask to go in normally , however token by null; If in String token There was a designation of @RequestParam(“token”), So the front end must have token When this key , Request to go in normally , If not, report 400 error .


@RequestBody From the front end json Data matching rules

Statement : According to Content-Type , etc. ,Spring-MVC Will take a different HttpMessageConverter Implementation to carry out information transformation and analysis .
          Here is the most commonly used : Front end to Content-Type by application/json, Pass on json String data ; Backend to @RequestBody
          When the model receives data .

analysis json Overview of the general process of data
        Http Transfer request body information , It will eventually be encapsulated in com.fasterxml.jackson.core.json.UTF8StreamJsonParser in ( Tips :Spring use CharacterEncodingFilter Set the default encoding to UTF-8), And then in public class BeanDeserializer extends BeanDeserializerBase implements java.io.Serializable in , adopt  public Object deserializeFromObject(JsonParser p, DeserializationContext ctxt) throws IOException Method To analyze .

Core logic analysis example :

        Let's say it's from the front end json The string is like this : {"name1":" Dunsullivan ","age":123,"mot":" I'm a little bird ~"} The back-end model is just name and age attribute , And corresponding setter/getter Method ; Give the general deserializeFromObject(JsonParser p, DeserializationContext ctxt) Methodical Core logic :


What do the attributes in the specified model correspond to key

Here is a brief introduction , For more information, please refer to :

           public class BeanPropertyMap implements Iterable<SettableBeanProperty>,java.io.Serializable

give Controller Test class in :

Give the properties in the model (setter/getter The method didn't cut it out ):

Use postman Test it , Example :

The figure above shows a simple test , But the measurement is not comprehensive , I won't take you to the test here , Give directly .


A comprehensive conclusion

Conclusion @JsonAlias annotation , Realization :json When turning the model , send json Specific in key Can be transformed into specific model attributes ; But the model turns json when ,
                After conversion key Still consistent with the property name , see : In the example above name Field request and response .
                The following figure further illustrates :

                  here ,json When a string is converted to a model ,json in key by Name Or for name123 Or for name All can be identified .

Conclusion @JsonProperty annotation , Realization :json When turning the model , send json Specific in key Can be converted to specified model attributes ; alike , model
                Type conversion json when , After conversion key For the specified key, see : In the example motto Field request and response .
                The following figure further illustrates :

                here ,json When a string is converted to a model ,key by MOTTO Recognizable , but key by motto Is not recognized .

Conclusion @JsonAlias Annotations need to depend on setter、getter, and @JsonProperty Annotations don't need .

Conclusion Without considering the above two annotations ,key When matching attributes , Default case sensitive .

Conclusion There are several identical key Of json In a string , When converting to a model , In the same way key in , The last one key The value of is given to the module
                Type attribute replication , because setter Will overwrite the original value . See... In the example gender attribute .

Conclusion Back end @RequestBody The class corresponding to the annotation will HTTP The input stream of ( With requester ) Assemble to target class ( namely :@RequestBody Back
                Class ) when , Will be based on json In the string key To match the properties of the corresponding entity class , If the match is consistent and json It's time to key Corresponding value
                accord with ( Or it can be converted to ) When the type of the corresponding property of the entity class requires , Will call entity class setter Method to assign a value to the property .

^_^  If there is anything improper , Welcome to correct

^_^  Code managed Links
               https://github.com/JustryDeng...RequestBody...

^_^  This article has been included in 《 Programmer growth notes ( Two )》, The author JustryDeng

原网站

版权声明
本文为[GuochaoHN]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240944364588.html