Difference between @RequestBody and @ResponseBody

Paramaters

@RequestBody

@ResponseBody

Purpose

Applicable for the incoming request data.

Applicable for the outgoing response data.

Method body

Used with POST, PUT, PATCH methods to read the request body.

Used with GET methods to write the response body.

Return value

Typically void or a simple type

Typically, a complex object representing the response data

Object

The deserialized object is passed as a method parameter.

The serialized object is returned from the method.

Payloads

Required to read JSON/XML request payloads.

Required to write JSON/XML response payloads.

Difference Between @RequestBody and @ResponseBody Annotation in Spring

To achieve the functionality of handling request data and response data in Spring MVC, @RequestBody and @ResponseBody annotations are used. So, in this article, we will go dive into the difference between @RequestBody and @ResponseBody annotations with an example.

@RequestBody

  • @RequestBody is mainly used with CRUD Operations to read the request body.

Example:

@PostMapping("/addStudent")
public void AddStudent(@RequestBody Student student) {
// body
}

@ResponseBody

  • @ResponseBody is typically used with GET methods to write the response body content.

Example:

@GetMapping("/getStudent")
@ResponseBody
public Student getStudent()
{
return student;
}

Similar Reads

Difference between @RequestBody and @ResponseBody

...

Example of @RequestBody and @ResponseBody Annotation:

Step 1: Set up a new Spring MVC project...

Contact Us