img

SpringBoot 使用注解@SensitiveWord过滤敏感词

旁观者 1年前 ⋅ 1957 阅读

网站或APP都要做敏感词过滤,利用AOP,自定义注解的方式实现敏感词过滤,减少代码嵌入,便于统一管理,同时也能提高开发效率

步骤:

1.添加关键词库sensitive-words.txt

2.自定义注解:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SensitiveWord {
    String[] value() default "";
}

3.自定义转换器

public interface Convert<T> {
    T convert(T t, String[] keyWords);
}

4.自定义过滤规则,继承转换器

@Component
public class SensitiveFilter<T> implements Convert<T> {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveFilter.class);

    /**
     * 替换符
     */
    private static final String REPLACEMENT = "***";


    /**
      * 根节点
       */
    private TrieNode rootNode = new TrieNode();

    @Override
    public T convert(T t, String[] keyWords) {
        List<String> keys = Arrays.asList(keyWords);
        keys.forEach(k -> update(t, k));
        return t;
    }

    /**
     * 反射赋值已过滤敏感词的参数
     * @param update
     * @param key
     * @return
     */
    public T update(T update, String key){
        try {
            Class<? extends Object> clazzUpdate = update.getClass();
            Field[] fields = clazzUpdate.getDeclaredFields();
            for (int i=0;i<fields.length;i++){
                Field field = fields[i];
                field.setAccessible(true);
                String name = field.getName();
                Class type=field.getType();
                Object value = field.get(update);
                String typeStr = type.toString();
                if(value!=null && typeStr.endsWith("String") && name.equals(key)){
                    String newValue = filter(value.toString());
                    field.set(update, newValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return update;
    }

    /**
     * 在构造器执行完之后初始化一次
     */
    @PostConstruct
    public void init() {
        try (
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"))
        ) {
            String keyword;
            while ((keyword = reader.readLine()) != null) {
                // 添加到前缀树
                this.addKeyword(keyword);
            }
        } catch (IOException e) {
            logger.error("加载敏感词文件失败: " + e.getMessage());
        }
    }

    /**
     * 将一个敏感词添加到前缀树中
     * @param keyword
     */
    private void addKeyword(String keyword) {
        TrieNode tempNode = rootNode;
        for (int i = 0; i < keyword.length(); i++) {
            char c = keyword.charAt(i);
            TrieNode subNode = tempNode.getSubNode(c);

            if (subNode == null) {
                // 初始化子节点
                subNode = new TrieNode();
                tempNode.addSubNode(c, subNode);
            }

            // 指向子节点,进入下一轮循环并设置结束标识
            tempNode = subNode;

            if (i == keyword.length() - 1) {
                tempNode.setKeywordEnd(true);
            }
        }
    }

    /**
     * 过滤敏感词
     *
     * @param text 待过滤的文本
     * @return 过滤后的文本
     */
    public String filter(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }

        // 指针1
        TrieNode tempNode = rootNode;
        int begin = 0;
        int position = 0;
        StringBuilder sb = new StringBuilder();

        while (position < text.length()) {
            char c = text.charAt(position);
            if (isSymbol(c)) {
                // 若指针1处于根节点,说明前面还没遇到疑似敏感词,将此符号计入结果,让指针2向下走一步
                if (tempNode == rootNode) {
                    sb.append(c);
                    begin++;
                }
                // 无论符号在开头或中间,指针3都向下走一步
                position++;
                continue;
            }

            // 检查下级节点
            tempNode = tempNode.getSubNode(c);
            if (tempNode == null) {
                // 以begin开头的字符串不是敏感词,进入下一个位置,重新指向根节点
                sb.append(text.charAt(begin));
                position = ++begin;
                tempNode = rootNode;
            } else if (tempNode.isKeywordEnd()) {
                // 发现敏感词,将begin~position字符串替换掉,然后进入下一个位置,重新指向根节点
                sb.append(REPLACEMENT);
                begin = ++position;
                tempNode = rootNode;
            } else {
                // 检查下一个字符
                position++;
            }
        }
        // 将最后一批字符计入结果
        sb.append(text.substring(begin));
        return sb.toString();
    }

    /**
     * 判断是否为符号
     * @param c
     * @return
     */
    private boolean isSymbol(Character c) {
        // 0x2E80~0x9FFF 是东亚文字范围
        return !CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
    }

    private class TrieNode {
        // 关键词结束标识
        private boolean isKeywordEnd = false;

        // 子节点(key是下级字符,value是下级节点)
        private Map<Character, TrieNode> subNodes = new HashMap<>();
        public boolean isKeywordEnd() {
            return isKeywordEnd;
        }

        public void setKeywordEnd(boolean keywordEnd) {
            isKeywordEnd = keywordEnd;
        }

        // 添加子节点
        public void addSubNode(Character c, TrieNode node) {
            subNodes.put(c, node);
        }
        // 获取子节点
        public TrieNode getSubNode(Character c) {
            return subNodes.get(c);
        }
    }

}

5.自定义AOP,实现注解切入

@Aspect @Component public class SensitiveAop implements ApplicationContextAware {

    private ApplicationContext context;

    @Before(value = "@annotation(sensitiveWord)")
    public void beforeMethod(JoinPoint point, SensitiveWord sensitiveWord) {
        Convert convert = context.getBean(SensitiveFilter.class);
        String[] keyWords = sensitiveWord.value();
        Object[] args = point.getArgs();
        for (Object o : args) {
            if(!isBaseType(o)){
                convert.convert(o, keyWords);
            }
        }
    }

    /**
     * 判断object是否为基本类型
     * @param object
     * @return
     */
    public static boolean isBaseType(Object object) {
        Class className = object.getClass();
        if (className.equals(java.lang.Integer.class) ||
                className.equals(java.lang.Byte.class) ||
                className.equals(java.lang.Long.class) ||
                className.equals(java.lang.Double.class) ||
                className.equals(java.lang.Float.class) ||
                className.equals(java.lang.Character.class) ||
                className.equals(java.lang.Short.class) ||
                className.equals(java.lang.Boolean.class) ||
                className.equals(java.lang.String.class)) {
            return true;
        }
        return false;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}

6.在方法上使用注解

@SensitiveWord(value = {"key"})


全部评论: 0

    我有话说: