What is `@RequestBody ` does?

@RequestBodySpringMVC框架中的注解,通常与POSTPUT等方法配合使用。当客户端发送包含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;
}

使用 @RequestBody 和自定义JSON属性名映射

# 对应请求示例(使用与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...
}

你可能感兴趣的:(SpringBoot,注解,SpringMVC,java)