What does the @RequestBody annotation do in Spring MVC?

What does the @RequestBody annotation do in Spring MVC?

A) It binds the body of an HTTP request to a method parameter
B) It binds HTTP headers to a method parameter
C) It binds query parameters to a method parameter
D) It binds path variables to a method parameter

Answer:

A) It binds the body of an HTTP request to a method parameter

Explanation:

The @RequestBody annotation in Spring MVC is used to bind the body of an HTTP request to a method parameter. This is particularly useful in RESTful web services where the request body contains JSON or XML data that needs to be converted into a Java object.

For example:


@RestController
public class MyRestController {

    @PostMapping("/api/users")
    public User createUser(@RequestBody User user) {
        // Logic to save the user
        return user;
    }
}

In this example, the @RequestBody annotation binds the JSON or XML data in the request body to the User object. The createUser() method can then process this data as a Java object, making it easier to work with in your application.

The @RequestBody annotation is essential for handling HTTP requests that contain complex data, ensuring that the data is properly deserialized into Java objects for processing.

Reference links:

Spring Boot Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top