Spring Boot Request Body
Overview
Amy web applications need to process client requests sent over HTTP. The HTTP POST method sends data to the server, which should be deserialized to convert to language-specific representation.
Spring framework provides @RequestBody annotation to deserialize requests.
What is Request Body?
Data sent over the request body can be of any format like json, XML, PDF, Http Forms, and many more. The Content-Type header indicates the server's understanding type of request.
A typical HTTP POST request looks like this:
Deserializing RequestBody to Domain Object Using @RequestBody Annotation
The @RequestBody annotation indicates that Spring should deserialize a request body into an object. This object is passed as a parameter in the handler method. To understand the working let's create an Employee domain class and corresponding controlelr handler.
Handler method
Invoking the method will return desired response.
We are sending JSON respresentation of our employee domain object in the request body and returing same content in the response body with http 201-created code.
Elevate your coding game with our Free Spring Boot course. Enroll today and learn to build efficient, modular, and maintainable Java applications.
Deserializing RequestBody to Map Using @RequestBody Annotation
In same cases we dont have domain specific object or dont want to create it. Any incoming request can be deserialized to map which allows system to accept any incoming request without modifying actual code.
Deserialized map will have key same as json key and and corresponding value associated with it.
Conclusion
- Spring provides @RequestBody annotation to deserialize the incoming payload into java object or map.
- The request body goes along with content-type header for handler method to understand and deserialize the payload.