项目实战—@Valid+自定义校验注解+全局异常处理器实现敏感词过滤

  1. 实现自定义校验注解
  2. 业务代码
    2.1 isValid返回false(推荐)
    2.2 isValid抛出异常
  3. 附录
    附录1:敏感词工具类
    附录2:异常类
    附录3:校验对象
    附录4:请求报文

需求:对前端的请求参数进行校验,判断是否含有配置的敏感单词。本方案采用的是SpringMVC框架下的@Valid+自定义注解+全局异常处理器实现。

1. 实现自定义校验注解

注解类:

import javax.validation.Constraint;
import javax.validation.Payload;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = ValidateWordValidator.class)
@Documented
public  @interface ValidateWord {


    String message() default "请求参数错误!";

    Class[] groups() default {};

    Class[] payload() default {};
}

2. 业务代码

需求:校验User对象的name字段以及infos集合中所有infoName字段的值是否携带敏感词;

@Slf4j
@RestController
public class FilterController {
    @PostMapping("/t2/pp")
    // User类详见附录3
    public String t2(@RequestBody  @Valid User user) {
        return JSON.toJSONString(user);
    }
}

请求报文详见:附录4

若“1. 实现自定义校验注解”所示,ValidateWordValidator.isValid抛出异常返回false需要不同的业务处理。

2.1 方式一:isValid返回false(推荐)

实现自定义校验器:

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Set;

@Slf4j
public class ValidateWordValidator implements ConstraintValidator {

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {

        Set hitSensitiveWords = WordUtil.hit(JSON.toJSONString(value));

        if (CollectionUtils.isEmpty(hitSensitiveWords)) {
            return true;
        } else {
            String word = String.join(",", hitSensitiveWords);
            //禁止默认消息返回
            context.disableDefaultConstraintViolation();
            //输出设置的信息
            context.buildConstraintViolationWithTemplate(word).addBeanNode().addConstraintViolation();
            return false;
        }
    }
}

全局异常处理器:

import com.alibaba.fastjson.JSON;
import com.tellme.anno.ValidateWord;
import com.xdf.pscommon.exception.AnnoSensitiveWordException;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.ConstraintViolationImpl;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.metadata.ConstraintDescriptor;
import java.util.*;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
   @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
    @ResponseBody
    public String validErrorHandler(MethodArgumentNotValidException e) {
        List errors = e.getBindingResult().getAllErrors();
        List results = new ArrayList<>();
        Set sensitiveSets = new HashSet<>();
        //遍历
        if (!CollectionUtils.isEmpty(errors)) {
            for (ObjectError error : errors) {
                ConstraintViolationImpl constraintViolation = error.unwrap(ConstraintViolationImpl.class);
                ConstraintDescriptor constraintDescriptor = constraintViolation.getConstraintDescriptor();
                constraintDescriptor.getAnnotation().annotationType();
                //特定注解
                if (ValidateWord.class.isAssignableFrom(constraintDescriptor.getAnnotation().annotationType())) {
                    String[] split = Objects.requireNonNull(error.getDefaultMessage()).split(",");
                    sensitiveSets.addAll(Arrays.asList(split));
                } else {
                    //其他异常
                    results.add(error.getDefaultMessage());
                }
            }
            if (!CollectionUtils.isEmpty(sensitiveSets)) {
                results.add(0, String.format("您所输入的内容中包含敏感词,请重新输入,敏感词:%s", String.join(" ", sensitiveSets)));
            }
        }
        return results.get(0);
    }
}

2.2 方式二:isValid抛出异常(不推荐)

当抛出特定的异常时,全局异常处理器捕获的是ValidationException.class异常。

@Slf4j
public class ValidateWordValidator implements ConstraintValidator {

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {

        Set hitSensitiveWords = WordUtil.hit(JSON.toJSONString(value));

        if (CollectionUtils.isEmpty(hitSensitiveWords)) {
            return true;
        } else {
            throw new ValidateWordException(String.join(",",hitSensitiveWords));
        }
    }
}

全局异常处理器

    @ExceptionHandler(value = {ValidationException.class})
    @ResponseBody
    public String apiIdempotentExceptionHandler(HttpServletRequest req, ValidationException e) throws IOException {
        Throwable cause = e.getCause();
        if (cause != null) {
            if (cause instanceof ValidateWordException) {
                //处理异常返回的信息、
                return String.format("命中关键字 %s",e.getMessage());

            }
        }
        return "系统异常";
    }

3. 附录

附录1:敏感词工具类

工具类:校验输入的字符串是否含义敏感词。

public class WordUtil {

    private static List sensitiveWords = Arrays.asList("色情", "暴力");

    public static List hit(String value) {
        List hitSensitiveWords = new ArrayList<>();
        String param = JSON.toJSONString(value);
        for (String sensitiveWord : sensitiveWords) {
            if (param.contains(sensitiveWord)) {
                hitSensitiveWords.add(sensitiveWord);
            }
        }
        return hitSensitiveWords;
    }
}

附录2:异常类

异常类:目的是全局异常处理器处理对应自定义注解

public class ValidateWordException extends RuntimeException{

    public ValidateWordException() {
    }

    public ValidateWordException(String message) {
        super(message);
    }

    public ValidateWordException(String message, Throwable cause) {
        super(message, cause);
    }

    public ValidateWordException(Throwable cause) {
        super(cause);
    }

    public ValidateWordException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

附录3:校验对象

注意:若自定义注解需要放在集合上,那么集合上需要使用@Valid注解才能生效,如下列代码所示:

@Data
public class User {

    private String id;

    @ValidateWord
    private String name;

    private int age;

    @Valid
    private List infos;

    @Data
    public static class Info{
        @ValidateWord
        private String infoName;

        private String infoAge;
    }

}

附录4:请求报文

将拦截User.name字段以及User.infos[0].infoName字段。

{"age":0,"infos":[{"infoAge":"20","infoName":"色情"},{"infoAge":"21","infoName":"zcds"}],"name":"中学生不能暴力"}

你可能感兴趣的:(项目实战—@Valid+自定义校验注解+全局异常处理器实现敏感词过滤)