控制服务端接收的字段和返回的字段

使用 JsonView 不返回用户密码

domain.User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Data
public class User {
public interface UserSimpleView {}
public interface UserDetailView extends UserSimpleView {}

@JsonView(UserSimpleView.class)
private Long id;

@JsonView(UserSimpleView.class)
private String username;

@JsonView(UserDetailView.class)
private String password;

@JsonView(UserSimpleView.class)
private String email;
}

controller.UserController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@RestController
@RequestMapping("/user")
public class UserController {
private UserService userService;

@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}

@GetMapping("/getAllBySimple")
@JsonView(User.UserSimpleView.class)
public List<User> getAllSimpleUser() {
return userService.getAllUser();
}

@GetMapping("/getAllByDetail")
@JsonView(User.UserDetailView.class)
public List<User> getAllDetailUser() {
return userService.getAllUser();
}
}

测试结果

1
2
3
4
$ curl localhost:8080/user/getAllBySimple
[{"id":1,"username":"jerry","email":"123@456.com"},{"id":2,"username":"tom","email":"abc@def.com"}]
$ curl localhost:8080/user/getAllByDetail
[{"id":1,"username":"jerry","password":"p@ssw0rd","email":"123@456.com"},{"id":2,"username":"tom","password":"us3rn@m3","email":"abc@def.com"}]

使用 @JsonIgnoreProperties 使得密码字段只写不可读

1
@JsonIgnoreProperties(value = {"password"}, allowSetters = true)

使用 @JsonIgnoreProperties 使得服务器自动忽略客户端传过来的 model 字段(即,客户端只读

1
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, allowGetters = true)

例子:https://github.com/JerryLi-X/springboot-jpa-mysql-demo