Spring REST
Last Updated on: February 17, 2021 am
Java JSON Data Binding
Data binding is the process of converting the JSON data to a Java POJO.
Also known as: Mapping, Serialization/Deserialization
Jackson Data Binding
Spring uses the Jackson Project behind the scenes.
Jacksong supports XML and JSON.
By Default, Jackson will call appropriate getter/setter methods.
JSON to Java POJO
Jackson will call setXXX()
methods
Java POJO to JSON
Jackson will call getXXX()
methods
Spring and Jackson Support
Spring will automatically handle Jackson Integration.
JSON data being passed to REST Controller is converted to POJO.
Java Object being returned from REST controller is converted to JSON.
Example
1 |
|
Ignore Unknown Properties
Add a new annotation: @JsonIgnoreProperties
1 |
|
REST HTTP
HTTP Request Message
- Request Line: the HTTP command
- Header Variables: Request Metadata
- Message Body: contents of Message
HTTP Response Message
- Request Line: server protocol and status code
- Header Variables: Response Metadata
- Message Body: contents of Message
Status Code
MINE Content Types
MINE - Multipurpose Internet Mail Extenstion
Basic Syntax: type/sub-type
Examples:
text/html
,text/plain
application/json
,application/xml
Client Tool
send HTTP requests - Postman
Spring REST Controller
@RestController
- Extension of
@Controller
- Handles REST request and responses
1 |
|
Note: Config Spring MVC just like previous. Then change @Controller
to @RestController
Retrieve JSON from POJO
1 |
|
Note: Jackson will automatically handle all the low-level operations to convert the POJO to JSON format objects and display in the Response Body.
Use @PathVariable for REST Endpoints
1 |
|
Exception Handling
1 |
|