➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
MediaType Annotations and HttpStatus | Here we will discuss @RequestBody, @ResponseBody, and HttpStatus.
@RequestBody and @ResponseBody in Spring REST
@ResponseBody
:- It is a return type representing non-String. Here, and returns in JSON/XML format. The object will be converted to JSON/XML.@RequestBody
:- It is a parameter (non-String). Here, JSON/XML is converted to an object.
Using @ResponseBody is optional because @RestController will take care of that. But @RequestBody annotation must be applied externally.
- @RequestBody should be used as the method parameter.
- It will read the HTTP Request Body (XML/JSON) and convert it to Object Format.
- Syntax:-
@RequestBody ClassName objectName
- The end client/consumer must specify one header parameter:-
'Content-Type:__'
- To send data from consumer to producer GET request is not supported. (GET request never supports @RequestBody).
Example Application
Create a Spring starter project and add the following dependencies:- Lombok, Spring Web.
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private Integer eid;
private String ename;
private Double esal;
}
@RestController
@RequestMapping("/employee")
public class EmployeeRestController {
@PostMapping("/read")
public ResponseEntity<String> readEmp(@RequestBody Employee employee) {
return ResponseEntity.ok(employee.toString());
}
}
Start the application. API:- http://localhost:8080/employee/read
Example JSON:-
{
"eid" : 10,
"ename" : "ABC",
"esal" : 300.2
}
It will create the following object:- Employee(eid=10, ename=ABC, esal=300.2)
Even { }
in the request body is a valid JSON, that indicates objects created with default values:- Employee(eid=null, ename=null, esal=null)
In the postman, in the body change the type to XML and try to send the below data:-
<Employee>
<eid>101</eid>
<ename>ABC</ename>
<esal>250.0</esal>
</Employee>
If we try to send XML Input using @RequestBody
but the application is not supporting XML, then FrontController returns Http Status – 415 Unsupported MediaType. Response:-
{
"timestamp": "2024-06-21T01:15:18.107+00:00",
"status": 415,
"error": "Unsupported Media Type",
"trace": "org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'application/xml;charset=UTF-8' is not supported...",
"message": "Content-Type 'application/xml;charset=UTF-8' is not supported.",
"path": "/employee/read"
}
Whereas If output XML (ResponseBody) is not supported then 406 – Not Acceptable.
To Enable XML support, Add XML Dependency in pom.xml file, and restart the application:-
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Different Combination
Accept | Return |
JSON | JSON |
XML | JSON |
XML | XML |
JSON | XML |
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private Integer eid;
private String ename;
private Double esal;
private Double hra;
private Double ta;
}
@RestController
@RequestMapping("/employee")
public class EmployeeRestController {
@PostMapping("/read")
public ResponseEntity<Employee> readEmp(@RequestBody Employee employee) {
var sal = employee.getEsal();
var hra = sal * 10 / 100.0;
var ta = sal * 6 / 100.0;
employee.setHra(hra);
employee.setTa(ta);
return ResponseEntity.ok(employee);
}
}
Sample XML Input:-
<Employee>
<eid>101</eid>
<ename>AA</ename>
<esal>1000.0</esal>
</Employee>
Sample JSON Input:-
{
"eid" : 999,
"ename" : "SYED",
"esal" : 500.0
}
Case#1:- Accept JSON and return JSON.
It is the default one. In body => raw => JSON.
Case#2:- Accept XML and return JSON.
In body => raw => XML. Send the XML data, it will return JSON data.
Case#3:- Accept XML and return XML.
In Headers mention KEY=Accept and VALUE=application/xml. In body => raw => XML.
Case#4:- Accept JSON and return XML.
In Headers mention KEY=Accept and VALUE=application/xml. In body => raw => JSON.
At a time only one type of input/output.
HttpStatus
- It indicates what is the final response status for a request.
- It is a global type i.e. every language can understand.
- It is the combination of Number and Code (message).
- For every request, one response is given.
- For every response, one status code is provided.
- These are categorized into 5 types.
Message | Code | Description | Sample Code |
Information | 1xx | Details about processing | 100, 101, 102, … |
Success | 2xx | Processed Successfully | 200, 201, 202, … |
Redirect | 3xx | Redirect Moved From one server/link to another server/link | 300, 301, 302, … |
Client Side Error | 4xx | User Data Problem, Invalid Format | 400, 401, 403, 404, … |
Server Side Error | 5xx | Issue in code. Exceptions like NullPointerException, SQLException | 500, 501, 502, … |
HttpStatus Success
- If the request is processed successfully (no exception/no error) then return Http Status 200 -OK
- For the current request something new data(Resource) is created at the server side – then Return Http Status 201-CREATED. (ex: Database Table#Row[inserted], one PDF is created..etc)
- For the Void type, the response recommended Status code is 204-No Content. For example, delete one record.
- Accepted Header Param is considered and expected data format is given back then return Http Status code – 202 Accepted.
Client Side Error
400 - BAD REQUEST
:- Input Data Type mismatch or required params missing then HTTP Status code is 400 -BAD Request. Ex:int sid = __URL?sid=ABC
404 - Not Found
:- If Entered URL, doesn’t match with any RestController method then FrontController returns 404-Not Found.405 - Method Not Allowed
:- If the code is GET type but the request is POST type then FrontController returns 405 – Method Not Allowed.406 - Not Acceptable
:- If we request using Accept= __ Header, Content-Type is not supported then FC returns 406 – Not Acceptable415 - Unsupported Media Type
:- If Request Body MediaType (Content-Type= _ ) is not supported then FrontController returns 415 – Unsupported Media Type401 - Unauthorized (Security)
:- Try to access the URL without Login.403- FORBIDDEN
:- (Security) [invalid role access]. Logged in as Clerk, but trying to access Manager Services.
See more:- HTTP response status codes
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!