@RequestBody
时间: 2023-10-01 12:05:54 浏览: 79
The @RequestBody annotation is used in Spring MVC to indicate that the method parameter should be bound to the request body. It is used to extract the incoming HTTP request body and convert it to a Java object. This is useful for handling complex HTTP requests that include JSON, XML or other types of data.
The @RequestBody annotation is typically used in conjunction with the @PostMapping, @PutMapping and @PatchMapping annotations, which are used for HTTP POST, PUT and PATCH requests respectively. When a request is made to the API endpoint with a content type of "application/json" or "application/xml", the @RequestBody annotation will automatically deserialize the request body and map it to the specified Java object.
For example, consider the following code snippet:
```
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
// create user logic
return ResponseEntity.ok(user);
}
```
In this example, the createUser method is annotated with @PostMapping and @RequestBody, indicating that it should accept an HTTP POST request with a JSON or XML payload. The method parameter, User user, is annotated with @RequestBody, telling Spring MVC to extract the request body and deserialize it to a User object. The method then creates the user and returns a ResponseEntity containing the created user object.
阅读全文