自定义注解进行数据脱敏

前言

有些时候,我们可能对输出的某些字段要做特殊的处理在输出到前端,比如:身份证号,电话等信息,在前端展示的时候我们需要进行脱敏处理,这时候通过自定义注解就非常的有用了。在Jackson中要自定义注解,我们可以通过**@JacksonAnnotationsInside**注解来实现,如下示例:

一、自定义注解

复制代码
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = SensitiveSerializer.class)
public @interface Sensitive {

    //加密开始位置
    int start()default 0 ;

    //加密结束位置
    int end() default 0 ;

    //加密掩码
    String mask() default "*" ;
}

二、自定义序列化处理器SensitiveSerializer

复制代码
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.Collections;

/**
 * @author songwp
 * @date 2024-11-15
 * @desc 自定义序列化器,用于对敏感字段进行脱敏处理
 */
public class SensitiveSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private Sensitive sensitive;

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String val = value;
        if (sensitive != null && StringUtils.hasLength(val)) {
            String m = sensitive.mask();
            int start = sensitive.start();
            int end = sensitive.end();
            int totalLength = value.length();
            if (totalLength <= 2) {
                val = totalLength == 1 ? value + m : value.substring(0, 1) + m;
            } else if (totalLength <= 6) {
                val = value.substring(0, 1) + String.join("", Collections.nCopies(totalLength - 2, m)) + value.substring(totalLength - 1);
            } else {
                int prefixLength = Math.min(start, totalLength - 1);
                int suffixLength = Math.min(end, totalLength - 1);
                if (prefixLength > totalLength) {
                    prefixLength = totalLength / 2;
                }
                if (suffixLength > totalLength) {
                    suffixLength = totalLength / 2;
                }
                int maskLength = Math.max(0, totalLength - (prefixLength + suffixLength));
                if (maskLength == 0) {
                    prefixLength -= 2;
                    suffixLength -= 2;
                    maskLength = Math.max(2, totalLength - (prefixLength + suffixLength));
                }
                prefixLength = Math.min(prefixLength, totalLength - 1);
                suffixLength = Math.min(suffixLength, totalLength - 1);
                maskLength = totalLength - prefixLength - suffixLength;
                val = value.substring(0, prefixLength) + String.join("", Collections.nCopies(maskLength, m)) + value.substring(totalLength - suffixLength);
            }
        }
        gen.writeString(val);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        sensitive = property.getAnnotation(Sensitive.class);
        return this;
    }
}

三、在输出的Java Bean中使用上面的注解

复制代码
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.songwp.config.Sensitive;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;

/**
 * @author songwp
 * @version 1.0
 * @date 2024-11-15
 * @description: user domain
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    @JsonSerialize(using = ToStringSerializer.class)
    private Long id;
    @Sensitive(start = 2, end = 4)
    private String name;
    @Sensitive(start = 6, end = 4)
    private String idCard;
    @Sensitive(start = 4, end = 3)
    private String phone;
}

四、在前端展示结果如下:

敏感数据得到了脱敏处理。

相关推荐
大圣编蚕5 分钟前
Spring AOP 失效排查:从原理到实战的完整指南
java·后端·spring
EatFan13 分钟前
MCP 从概念到落地:Java(Spring AI Alibaba)与 .NET 双栈接入实操对比
java·人工智能·后端·spring·.net·java后端·mcp
专业程序开发源13 分钟前
springboot全民健身和饮食健康管理系统29158-计算机课程设计、毕业设计
java·spring boot·后端·python·django·php·课程设计
ym hyd 11116 分钟前
汽车零部件缺陷管理系统源码 Java+SpringBoot+Vue3 前后分离
java·vue.js·spring boot·汽车·毕设
Wang's Blog35 分钟前
Java框架 SpringCloud 快速入门: 从服务拆分到注册中心的落地路线
java·开发语言·spring cloud
Wang's Blog1 小时前
Java框架 SpringCloud 快速入门: 全局过滤器(GlobalFilter)自定义鉴权
java·开发语言·spring cloud
paopaokaka_luck1 小时前
高校社团管理(AI辅助任务分配、协同过滤算法推荐、ECharts数据可视化、活动参与闭环、校园交流与反馈、器材借还管理)
java·前端·javascript·spring boot·数据分析·echarts
vx_Biye_Design1 小时前
springboot小区管理系统68491-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·spring·课程设计·express
专业程序开发源1 小时前
springboot外卖系统94294-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·spring·php·课程设计
Moshow郑锴3 小时前
sql-pipeline - 基于PostgreSQL的SQL健康检查与发布编排平台
java·sql