RequestBody annotation in Spring

The @RequestBody annotation can be used for handling web requests.

java-featured-image

More specifically, it is used to bind a method parameter with the body of a request and the way it works is HttpMessageConverter converts the request’s body based on the type of the content of the request.

Syntax

<modifier> <return-type> <method-name> (@RequestBody <type> <name>) {

}

An example of the above syntax:

public String congratulateEmployee(@RequestBody Employee emp) {

}

A full Controller class containing the above method:

@RestController
public class CongratulationsController {	
	@PostMapping("/congratulations")
	public Manager assignToManager(@RequestBody Employee emp) {
	   String name = emp.getName();
	   int yearsWorked = emp.getYearsWorked();
	   String message = "Congratulations, " + name + "! You have been working here for " + yearsWorked + ".";
	   Manager manager = new Manager();
	   manager.setEmployee(emp.getName()); // now this employee has been assigned to this manager
	   return manager;
	}	
}

Our Employee class looks like this:

public class Employee {
   private String name;
   private int yearsWorked;

   public String getName() {
      return name;
   }

   public int getYearsWorked() {
      return yearsWorked;
   }
}

Our Manager class looks like this:

public class Manager {
	private String employee;
	
	public void setEmployee(String name) {
		employee = name;
	}
	
	public String getEmployee() {
		return employee;
	}
}




Breakdown

As I said above, the JSON format we are receiving is deserialized into a Java type.

When we said @RequestBody Employee emp we binded the method parameter of type Employee with the body of the web request. The RequestBody arrives as follows:

{
 "name": "John Doe", 
 "yearsWorked": "3"
}

Again, thanks to HttpMessageConverter method, we can convert that RequestBody JSON response to Employee object, which contains the public methods getName() and getYearsWorked(). This is why we can call these methods on the RequestBody parameter:

String name = emp.getName(); 
int yearsWorked = emp.getYearsWorked();

As a result of the method, we have returned data of type “Manager” and thanks to the HttpMessageConverter we have converted the return type to the following response format:

{
  "employee": "the name of the employee that was contained in the @RequestBody"
}

As a side note, the RequestBody annotation, just like the RestController annotation, is mostly used in REST APIs.

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments