Spring Certified Professional 2023 · Free Practice Question Easy
Question 9
Which annotation is used to enable reading and deserialization of the request body?
-
A
@RequestParam -
B
@ResponseBody -
C
@PathVariable -
D
@RequestBody
Reveal correct answer
Correct answer: D
Explanation
The @RequestBody annotation is a parameter-level annotation in Spring that is used to indicate that the incoming HTTP request body should be mapped to the annotated method parameter. It is commonly used in Spring MVC controllers to handle requests that send data in the request body, such as JSON or XML payloads.
When the @RequestBody annotation is applied to a method parameter, Spring automatically converts the incoming request body data to the corresponding Java object based on the specified mapping, such as JSON to Java object conversion using a JSON parser. It uses the configured HttpMessageConverter implementations to perform the conversion.
Here's an example that demonstrates the usage of @RequestBody:
- @RestController
- public class UserController {
- @PostMapping("/users")
- public ResponseEntity<User> createUser(@RequestBody User user) {
- // Logic to create a new user using the received User object
- // ...
- return ResponseEntity.ok(user);
- }
- }
In the above example, the createUser method is annotated with @PostMapping to handle POST requests to the /users endpoint. The @RequestBody annotation is applied to the User parameter, indicating that the incoming request body should be converted to a User object and passed to the method.
By using the @RequestBody annotation, Spring simplifies the process of binding request data to method parameters, allowing for easy handling of request payloads in a flexible and convenient way.
Springdoc:
public @interface RequestBody
Annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with @Valid.
Supported for annotated handler methods.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
