Hello guys, if you are wondering what is
@RequestBody and
@ResponseBody annotation in Spring MVC and Spring Boot then you have come to the right place. Earlier, I have told you
about the
@RestController
annotation and in this article, I am going to explain to you what is RequestBody
and ResponseBody annotation, how to use them, and when to use them with simple examples. While working with REST API, we may need to bind HTTP requests and response bodies
with the domain object. To bind this, we use we can use the @ResponseBody and @RequestBody annotations in Spring MVC.
These two annotations will take care of everything required to convert JSON request to Java object by using HttpMessageConverter, so that you can work directly with object without worrying about converting JSON to Java object form Request and converting Java object to JSON message while sending response.
So in this
tutorial, we are going to discuss what and when to use the
@ResponseBody and
@RequestBody in
Spring MVC.
So let's create the REST controller to accept the student registration. So there is no need to have converted the HTTP request to an object. The Spring is responsible for automatically deserializing the JSON into a Java based object using the HTTPMessageConverter.
As mentioned above, spring is capable of deserializing the JSON into a Java type assuming the appropriate one is specified. But keep in your mind that, the type that we annotate with the @RequestBody annotation must correspond to the JSON object that we sent through the client side.
Note: We need to add the following changes if we don't have the @RestController annotation.
So this is all about the @ResponseBody annotation in Java and Spring applications. These are two of the many essential Spring MVC annotations a Java developer should know but if you have created any REST API or RESTful web service in Java then you will most likely be using these two annotations for sure along with @RestController and other REST API Annotation from Spring Framework.
That's all about what are @ResponseBody and @RequestBody annotation in Spring Framework? They are essential annotations to create REST API and RESTful web services in Java using Spring Framework, and they are the reasons why it's so easy to create RESTful web services using Spring Framework for Java developers.
How to use RequestBody and ResponseBody annotations in Spring MVC
First, have a look at @ResponseBody annotation and its use cases.
1. @RequestBody Annotation in Spring and Spring Boot
The @RequestBody annotation is responsible for binding the HTTPRequest body to the body of the web request. Depending on the content type of the request, the body of the request is given through a HttpMessageConverter, which resolves the method argument.
We can also use the
@Valid annotation to
automatically validate the input.
In brief, the @RequestBody annotation is responsible for retrieving the request body and automatically converting it to the Java object.
In brief, the @RequestBody annotation is responsible for retrieving the request body and automatically converting it to the Java object.
Let's have an example to explain this.
Student registration
Student registration
model.package com.school.model;
public class Student { private String firstName; private String lastName; private int age; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
So let's create the REST controller to accept the student registration. So there is no need to have converted the HTTP request to an object. The Spring is responsible for automatically deserializing the JSON into a Java based object using the HTTPMessageConverter.
@RestController @RequestMapping("/school/api") public class StudentController { @Autowired private StudentRepository studentRepository; @GetMapping("/students") public List < Student > getAllStudents(); @GetMapping("/students/{id}") public ResponseEntity < Student > getStudentById(@PathVariable(value = "id") Long studentId) { Student student = studentRepository.findById(studentId); if (student == null) { return new ResponseEntity(errors, HttpStatus.SERVICE_UNAVAILABLE); } return new ResponseEntity(student, HttpStatus.OK); } @PostMapping("/students") public Student addStudent(@Valid @RequestBody Student student) { return studentRepository.save(student); } }
As mentioned above, spring is capable of deserializing the JSON into a Java type assuming the appropriate one is specified. But keep in your mind that, the type that we annotate with the @RequestBody annotation must correspond to the JSON object that we sent through the client side.
I will show the API request which is sent through the
Postman in order to send the data to the backend.
So this is above the
@RequestBody annotation and
let's discuss the
@ResponseBody
annotation.
JSON or XML and send this information back as a part of the HTTP response. When working with the REST API, we should use @RestController on a class level rather than @ResponseBody on a method level.
2. @ResponseBody Annotation in Spring and Spring Boot
The @ResponseBody annotation is telling that the Spring framework serializes a return object intoJSON or XML and send this information back as a part of the HTTP response. When working with the REST API, we should use @RestController on a class level rather than @ResponseBody on a method level.
The @RestController is a constructed annotation with
@Controller and
@ResponseBody that is itself a meta-annotation. The student class which is
created will be the same as for this example also.
When we send a
POST request to our REST controller, we will get the response as below.
application/json;charset=UTF-8
transfer-encoding:chunked
date:Tue, 14 Sep 2021 18:49:39 GMT
{ "firstName": "James", "lastName": "Robert", "age": 30 }
Note: We need to add the following changes if we don't have the @RestController annotation.
@Controller public class StudentController { @Autowired private StudentService studentService; @PostMapping("/student-registration") public @ResponseBody Student register(@RequestBody Student student) { return studentService.saveStudentDetail(mapStudentData(student)); } }
So this is all about the @ResponseBody annotation in Java and Spring applications. These are two of the many essential Spring MVC annotations a Java developer should know but if you have created any REST API or RESTful web service in Java then you will most likely be using these two annotations for sure along with @RestController and other REST API Annotation from Spring Framework.
That's all about what are @ResponseBody and @RequestBody annotation in Spring Framework? They are essential annotations to create REST API and RESTful web services in Java using Spring Framework, and they are the reasons why it's so easy to create RESTful web services using Spring Framework for Java developers.
You can map your values to the model you defined in your system for
handling any specific call by using the
@RequestBody
annotation. On the other hand, using
@ResponseBody, you can send
anything back to the source of the request. Both of these items can be
readily mapped without the need to write a custom parser or
anything.
Other Spring and REST Resources you may like
Thanks a lot for reading this article so far. If you like this Java, REST, and Spring MVC tutorial then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.
- How to create RESTful Web Service in Java using Spring
- Spring Boot + Angular Example for Fullstack Developers
- What is the use of DispatcherServlet in Spring MVC?
- How to use MyBatis with Spring Boot in Java?
- 20+ Spring Boot Interview Questions with Answers
- Spring Boot + React.js example for Java developers
- 6 Best Courses to learn Spring Framework
- How to log SQL in a Spring Boot application?
- 15 Spring Data JPA Interview Questions with Answers
- How to fix No Spring Bean found of Type using @Autowired
- My Favorite Spring Boot Courses for Java programmers
- How to use @SpringBootTest annotation in Java
- 25+ Spring Security Interview Questions with Answers
- 5 Best Courses to learn Reactive Spring and WebFlux
- How to enable Spring security in a Java web application?
Thanks a lot for reading this article so far. If you like this Java, REST, and Spring MVC tutorial then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.
P. S. - If you want to learn the Spring Boot framework from
scratch and look for some of the best online resources, you can also
check out these best Spring Boot courses for Java developers. This article contains the best Udemy and Pluralsight courses to
learn Spring Boot from scratch.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.