fastjson 自定义过滤器实现数据关键字段脱敏(含代码示例)。FastJson, 自定义过滤器, Java注解, JSON脱敏, ValueFilter, 字段脱敏, WebMvcConfigurer, JSON序列化
在 Java Web 开发中,为了满足敏感数据保护的需求,FastJson 提供了 ValueFilter
接口用于实现字段级别的脱敏处理。本文将详细介绍如何通过自定义注解和 ValueFilter
实现 JSON 脱敏功能。
一、实现核心代码
1. 自定义注解定义
定义一个注解 @FastJsonFilter
,用于在字段上标识脱敏类型:
复制
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FastJsonFilter {
FilterType filterType() default FilterType.NULL;
enum FilterType {
NAME,
PASSWORD,
PHONE,
ID_CARD,
NULL
}
}
2. 自定义 FastJson ValueFilter 实现
使用 ValueFilter
接口进行字段处理逻辑扩展:
复制
import com.alibaba.fastjson.serializer.ValueFilter;
import com.common.annotation.FastJsonFilter;
import java.lang.reflect.Field;
public class FastJsonValueFilter implements ValueFilter {
public static final int PHONE_LENGTH = 11;
public static final int ID_CARD_LENGTH = 18;
public static final String NAME_REGEX = "(\\d)\\d.*";
public static final String PHONE_REGEX = "(\\d{3})\\d{4}(\\d{4})";
public static final String ID_CARD_REGEX = "(\\d{6})\\d{8}(\\w{4})";
@Override
public Object process(Object object, String name, Object value) {
try {
Field field = object.getClass().getDeclaredField(name);
return getFormatValue(field, value);
} catch (Exception e) {
return value;
}
}
private static Object getFormatValue(Field field, Object value) {
if (field.isAnnotationPresent(FastJsonFilter.class)) {
return format(field.getAnnotation(FastJsonFilter.class).filterType(), value);
}
return value;
}
private static Object format(FastJsonFilter.FilterType filterType, Object object) {
if (filterType == FastJsonFilter.FilterType.NULL || object == null) return null;
String value = object instanceof String ? (String) object : null;
if (value == null) return null;
switch (filterType) {
case NAME:
return value.replaceAll(NAME_REGEX, "$1*$2");
case PASSWORD:
return "******";
case PHONE:
return value.length() == PHONE_LENGTH ? value.replaceAll(PHONE_REGEX, "$1****$2") : null;
case ID_CARD:
return value.length() == ID_CARD_LENGTH ? value.replaceAll(ID_CARD_REGEX, "$1********$2") : null;
default:
return null;
}
}
}
二、注解使用示例
以一个 User
类为例,演示如何使用该注解:
复制
public class User {
public User(String userName, String password, String phone) {
this.userName = userName;
this.password = password;
this.phone = phone;
}
public User() {}
@FastJsonFilter(filterType = FastJsonFilter.FilterType.NAME)
private String userName;
@FastJsonFilter(filterType = FastJsonFilter.FilterType.PASSWORD)
private String password;
private String avatar;
@FastJsonFilter(filterType = FastJsonFilter.FilterType.PHONE)
private String phone;
}
三、序列化使用方式
使用自定义过滤器序列化对象:
复制
String json = JSONObject.toJSONString(new User(), new FastJsonValueFilter());
四、统一配置(可选)
为了统一全局 JSON 序列化行为,可通过实现 WebMvcConfigurer
接口,在 Spring Boot 中配置消息转换器,使所有返回的对象默认使用该脱敏策略。
通过以上方法,可以优雅地为 Spring Boot 项目实现 FastJson 自定义字段脱敏处理,有效保护用户敏感信息。
作者:https://blog.xn--rpv331d.com/望舒
链接:https://blog.xn--rpv331d.com/望舒/blog/9
转载注意保留文章出处...
No data