@RequestBody
时间: 2023-10-01 09:05:55 浏览: 58
解读@RequestBody的正确使用方法
@RequestBody is an annotation in Spring Boot that is used to bind the HTTP request body with a method parameter in a controller. It is used to extract the request payload from a POST or PUT request and converts it into a Java object. This annotation is used in the controller method signature and is followed by the Java object class to which the request payload is to be converted.
For example, consider the following code snippet:
```
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
User savedUser = userService.save(user);
return new ResponseEntity<>(savedUser, HttpStatus.CREATED);
}
```
In the above code, the @RequestBody annotation is used to bind the request body to the User object. The User object is then passed to the createUser() method as a parameter. The createUser() method saves the user and returns a ResponseEntity with the saved user and HTTP status code.
Overall, @RequestBody is a powerful annotation that simplifies the process of extracting data from the request payload and converting it into a Java object.
阅读全文