Friday, September 23, 2022

How to use @ResponseBody and @RequestBody in Spring MVC and REST? Example Tutorial

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



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. 


Let's have an example to explain this.




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;
    }
}


What is @ResponseBody and @RequestBody in Spring MVC? When to use them with Examples

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.




2. @ResponseBody Annotation in Spring and Spring Boot

The @ResponseBody annotation is telling that the Spring framework serializes a return object into
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. 

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. 

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 developersThis 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.