@RequestBody
是SpringMVC
框架中的注解,通常与POST
、PUT
等方法配合使用。当客户端发送包含JSON或XML格式数据
的请求时,可以通过该注解将请求体内容
绑定到Controller方法参数
上
自动反序列化:
SpringMVC
会根据@RequestBody
注解的参数类型,利用Jackson
库(默认配置下)或其他MessageConverter
将HTTP请求体中的JSON或XML数据转换成对应的Java对象。
支持复杂数据结构:
可以轻松处理嵌套对象
、数组
、集合
等复杂数据结构,将其映射为Java实体类
或自定义对象
。
# 对应请求示例(假设User类有username和password属性):
POST /users HTTP/1.1
Content-Type: application/json
{
"username": "john.doe",
"password": "secret"
}
@PostMapping("/users")
public User createUser(@RequestBody User user) {
// 将请求体中的JSON或XML数据转换为User对象
userService.save(user);
return user;
}
# 对应请求示例:
POST /users HTTP/1.1
Content-Type: application/json
{
"username": "john.doe",
"password": "secret",
"address": {
"street": "123 Main St.",
"city": "Springfield"
}
}
@PostMapping("/users")
public User createUser(@RequestBody UserRequest userRequest) {
User user = new User();
user.setUsername(userRequest.getUsername());
user.setPassword(userRequest.getPassword());
user.setAddress(userRequest.getAddress());
userService.save(user);
return user;
}
public class Address {
private String street;
private String city;
// getters and setters...
}
public class UserRequest {
private String username;
private String password;
private Address address;
// getters and setters...
}
# 对应请求示例(创建多个用户):
POST /batch/users HTTP/1.1
Content-Type: application/json
[
{
"username": "user1",
"password": "pass1"
},
{
"username": "user2",
"password": "pass2"
}
]
@PostMapping("/batch/users")
public List<User> createUsers(@RequestBody List<UserRequest> userRequests) {
List<User> users = new ArrayList<>();
for (UserRequest request : userRequests) {
User user = new User();
// map request properties to user object...
users.add(user);
}
userService.saveAll(users);
return users;
}
# 对应请求示例(使用与Java字段不同的JSON属性名):
POST /users HTTP/1.1
Content-Type: application/json
{
"user_name": "john.doe",
"pwd": "secret"
}
@PostMapping("/users")
public User createUser(@RequestBody UserRequest userRequest) {
User user = new User();
user.setUsername(userRequest.getUsername());
user.setPassword(userRequest.getPassword());
userService.save(user);
return user;
}
public class UserRequest {
@JsonProperty("user_name")
private String username;
@JsonProperty("pwd")
private String password;
// getters and setters...
}