In this post, I’d like to explain the use of the @RequestBody annotation in Java web application development with the Spring framework and Spring MVC. You’ll gain a better understanding of this annotation through the code examples provided below, which will make developing applications with Spring MVC easier.

 

1. What is @RequestBody annotation?

According to its official Javadocs, the @RequestBody annotation is used to annotate a parameter in a controller’s handler method, indicating that the parameter should be bound to the body of the web request. Depending on the content type of the request, an HttpMessageConverter will deserialize the data in the request body into a Java object of the type specified by the annotated parameter.

For example, if the content type of the request is application/json, the JSON document in the body will be read and deserialized into a Java object, which will then be passed as an argument to the handler method.


2. Understand @RequestBody annotation by code examples

Let’s go through some code examples to better understand this annotation. Suppose a request carries the following JSON document in its body:

{
    "email": "john.doe@gmail.com",
    "fullName": "John Doe"
}
On the server side, we have a POJO (Plain Old Java Object) that looks like this:

package net.codejava;

public class User {
	private int id;
	
	private String email;
	
	private String fullName;
	
	// getters and setters not shown for brevity
}
You can see that this Java class has fields matching those in the JSON object. We can then use the @RequestBody annotation in the handler method as follows:

package net.codejava;

@RestController
public class UserController {


	@PostMapping("/users")
	public ResponseEntity<?> save(@RequestBody User user) {
		
		// use the User object deserialized from request body...
		
	}
}
Here, the user parameter of type User is annotated with @RequestBody annotation. Suppose a client sends a request using curl as follows:

curl -H "Content-Type: application/json" 
-d "{\"email\": \"john.doe@gmail.com\", \"fullName\": \"John Doe\"}" 
localhost:8080/users
On the server side, Spring MVC detects that the request content type is application/json, so it invokes JsonbHttpMessageConverter to read the body and convert the JSON document into a Java object of type User, with the fields populated by the corresponding values from the JSON object.



I recommend you watch the following video to see a real-world usage of this annotation in a Java Spring project:


3. What if no matching fields in the Java class?

In the example above, the JSON object in the request body doesn’t have an id field, which is declared in the User class. In this case, any unmatched fields in Java object will have default values, e.g., null for the user ID in this example.


4. The @RequestBody’s required attribute

The @RequestBody annotation has only one attribute: required. By default, it is set to true, meaning that if the request body is missing, the server will return an HTTP status code 400 (Bad Request) to the client.

In case you want to allow for an optional request body, you should check for nullability of the parameter, as shown in the following example:

@PostMapping("/users")
public User save(@RequestBody(required = false) User user) {
	
	if (user != null) {
		// use the User object deserialized from request body...
	} else {
		// handle null parameter ...
	}
}
 

5. Specify other parameters in handler method

Certainly, you can specify additional parameters besides the one annotated with the @RequestBody annotation. For example:

@PostMapping("/users")
public User save(@RequestBody(required = false) User user, Model model, HttpServletRequest request) {
	...
}
Of course, this annotation is used to annotate only one parameter in the handler method.

 

Summary

Using @RequestBody annotation is a convenient way to have content (a JSON or XML document) in a request body automatically read and deserialized into a Java object, which is then passed as an argument to the handler method in a Spring MVC controller class. Imagine if you had to manually write code to parse the request body and construct Java objects - it would be time-consuming and error-prone. This annotation saves developers a lot of time, right?

That’s why the @RequestBody annotation is commonly used in REST API development with the Spring framework and Spring MVC.

 

References:

 

Other Spring Annotations:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment