概要
自定义注解+Adf敏感词校验
整体架构流程
自定义注解:校验指定类中的指定属性
```java
@Target({ ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SensitiveWord {
Class<?> sensitiveDto() ;
String[] filedNames() ;
}
利用反射获取对应属性值
@Aspect
@Component
@Slf4j
public class SensitiveWordAspect {
@Pointcut("@annotation(**.**.SensitiveWord)")
public void sensitiveWordCut(){}
@Before( "sensitiveWordCut()")
public void doAround(JoinPoint joinPoint) {
Method method = JoinPointMethodUtil.currentMethod(joinPoint);
SensitiveWord annotation = method.getAnnotation(SensitiveWord.class);
Object[] args = joinPoint.getArgs();
for(Object o:args){
Class<?> aClass = o.getClass();
if(aClass.equals(annotation.sensitiveDto())){
String[] strings = annotation.filedNames();
if(strings!=null&&strings.length>0){
Arrays.asList(strings).forEach(f->{
try {
Field field = aClass.getDeclaredField(f);
field.setAccessible(true);
Object o1 = field.get(o);
if(o1!=null){
String string = o1.toString();
if(SensitiveWordUtil.contains(string,SensitiveWordUtil.LONG_MATCH)){
throw new MyException("包含敏感词汇:"+JSON.toJSONString(SensitiveWordUtil.getSensitiveWord(string,SensitiveWordUtil.LONG_MATCH)));
}
}
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
}
}
}
}
}
此处引用工具类添加链接描述
为方便维护字典持久化到数据库同时初始化map
@GetMapping("/initMap")
@ApiOperation("初始化map")
public void initMap(){
List<String> list=sensitiveWordService.getList();
SensitiveWordUtil.initSensitiveWordMap(list);
}
服务启动时初始化map
@Component
@Slf4j
public class MyStartupRunner implements CommandLineRunner {
private final SensitiveWordController sensitiveWordController;
public MyStartupRunner(SensitiveWordController sensitiveWordController) {
this.sensitiveWordController = sensitiveWordController;
}
@Override
public void run(String... args) throws Exception {
log.info("启动时调用了。。。。");
sensitiveWordController.initMap();
}
}
注解使用
@PostMapping
@ApiOperation("保存")
//针对入参MyDTO对象的属性title和content进行敏感词校验
@SensitiveWord(sensitiveDto = MyDTO.class,filedNames = {"title","content"})
public Result save(@RequestBody MyDTO dto)