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;
}
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. |
Example of @RequestBody and @ResponseBody Annotation:
Step 1: Set up a new Spring MVC project
-
Create a new Maven project in your preferred IDE (e.g., IntelliJ or Eclipse or Spring Tool Suite) and add the following dependencies.
- Spring web
- Spring Data JPA
- MySQL Driver
<? xml version = "1.0" encoding = "UTF-8" ?>
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" >
< modelVersion >4.0.0</ modelVersion >
< parent >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-starter-parent</ artifactId >
< version >3.2.0</ version >
< relativePath /> <!-- lookup parent from repository -->
</ parent >
< groupId >com.spring</ groupId >
< artifactId >Employee_Management</ artifactId >
< version >0.0.1-SNAPSHOT</ version >
< name >Employee_Management</ name >
< description >Demo project for Employee_Management</ description >
< properties >
< java.version >17</ java.version >
</ properties >
< dependencies >
< dependency >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-starter-data-jpa</ artifactId >
</ dependency >
< dependency >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-starter-web</ artifactId >
</ dependency >
< dependency >
< groupId >com.mysql</ groupId >
< artifactId >mysql-connector-j</ artifactId >
< scope >runtime</ scope >
</ dependency >
< dependency >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-starter-test</ artifactId >
< scope >test</ scope >
</ dependency >
</ dependencies >
< build >
< plugins >
< plugin >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-maven-plugin</ artifactId >
</ plugin >
</ plugins >
</ build >
</ project >
|
Project Structure
Step 2: Configure MySQL Database:
spring.datasource.url=jdbc:mysql://localhost:3306/employee_management_system
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
Note: Please use username and password that are used in database.
Step 3: Create Model Class:
package com.demo.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity public class Employee {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
private String Name;
private String Address;
private int Salary;
public Employee()
{
super ();
// TODO Auto-generated constructor stub
}
public Employee(Long id, String name, String address,
int salary)
{
super ();
this .id = id;
Name = name;
Address = address;
Salary = salary;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this .id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAddress() {
return Address;
}
public void setAddress(String address)
{
Address = address;
}
public int getSalary() {
return Salary;
}
public void setSalary( int salary) {
Salary = salary;
}
} |
Step 4: Create Repository Interface:
package com.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.demo.model.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
} |
Step 5: Create Controller:
package com.demo.controller;
import com.demo.model.Employee;
import com.demo.repository.EmployeeRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller @RequestMapping ( "/emp" )
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@ResponseBody
@PostMapping
public Employee
addPerson( @RequestBody Employee employee)
{
return employeeRepository.save(employee);
}
@ResponseBody
@GetMapping
public List<Employee> getAllEmployee()
{
return employeeRepository.findAll();
}
@ResponseBody
@GetMapping ( "/{id}" )
public Employee getEmployeeById( @PathVariable Long id)
{
return employeeRepository.findById(id).orElse( null );
}
} |
Step 6: Run the Application
Now, You can run the Spring Boot application from IDE or by using the command-line tool provided by Spring Boot.
mvn spring-boot:run
Step 7: Test the Url: Use Postman
POST: http://localhost:8080/emp — Post the employee data
GET: http://localhost:8080/emp — Get all employee details
GET: http://localhost:8080/emp/{id} — Get the employee details by Id