Springboot返回内容屏蔽部分字段方法
屏蔽概念
假设有一个 User 对象,我们需要将这个 User 返回给前端,但是有些字段比较敏感(如:user.password ),需要屏蔽;
@Data
public class User{
private String username;
private String password;
}
双向屏蔽
前端提交上来的表单会忽略 password , 后端返回的 User 也会忽略 password;
只需在 password 字段上添加 @JsonIgnore 注解即可;
@Data
public class User{
private String username;
@JsonIgnore
private String password;
}
后端返回屏蔽(序列化时屏蔽)
添加 @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 注解;
@Data
public class User{
private String username;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
}
前端提交屏蔽(反序列化时屏蔽)
@Data
public class User{
private String username;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String password;
}