Spring AOP @PathVariable和@RequestParam 參數進行校驗(valid)

在上一篇文https://juejin.im/post/5a5e1159518825732b19d8ce,經過AOP對@RequestBody註解進行的參數進行校驗 那麼對於 @PathVariable和@RequestParam 卻沒有對應的spring mvc 默認自帶的校驗機制 @Valid + BindingResult。那麼此時該校驗的話,只能代碼上逐一進行校驗。java

先說明一下@PathVariable和@RequestParam;兩個註解的用法。spring

1.原版本講解

1.1 @PathVariable

1.1.1 RESTful風格

格式:path/1/catalpaFlat eg:mvc

@GetMapping("path/{isInt}/{isString}")
public ResponseVO pathGet(@PathVariable Integer isInt, @PathVariable String isString) {
   log.info("int:" + isInt);
   log.info("String:" + isString);
  JSONObject resultJson = new JSONObject();
  resultJson.put("isInt", isInt);
  resultJson.put("isString", isString);
  return new ResponseVO(HttpStatus.OK.value(), "pathGet", resultJson);
}
複製代碼

request: http://localhost:8888/path/3/dadasapp

1.1.2 校驗

代碼式校驗post

if(isInt < 2){
  return new ResponseVO(HttpStatus.BAD_REQUEST.value(), "pathGet", "isInt must be more than 2");
}
複製代碼

代碼式校驗的話,我的以爲就有點兒沒必要要,除非是一些特殊需求測試

1.2 @RequestParam

1.2.1 表單提交(query)

格式:query?isInt=2&isString=catalpaFlatspa

@GetMapping("query?")
public ResponseVO queryGet(@RequestParam Integer isInt, @RequestParam String isString) {
    log.info("int:" + isInt);
    log.info("String:" + isString);
    JSONObject resultJson = new JSONObject();
    resultJson.put("isInt", isInt);
    resultJson.put("isString", isString);
    return new ResponseVO(HttpStatus.OK.value(), "queryGet", resultJson);
}
複製代碼

1.2.2 校驗

一樣也須要代碼式校驗code

if(isInt < 2){
  return new ResponseVO(HttpStatus.BAD_REQUEST.value(), "queryGet", "isInt must be more than 2");
}
複製代碼

由於@Valid + BindingResult只能用於@ResponseBody這種類型註解。cdn

2. AOP改良版

能夠感覺到原版本都得在代碼中進行校驗,只要使用到@PathVariable和@RequestParam的都得進行一波參數校驗,所以就想能不能像@Valid同樣,爲其添加註解式校驗,這樣代碼量就減小並讓代碼優雅了不少。blog

2.1 接口層(IDAL)

如下代碼再則是改良以後的代碼:

  • @ParameterValid 至關於@Valid,而且在其屬性中進行配置參數校驗規則
  • @PathAndQueryParamValid 至關於AOP的切入點
@PathAndQueryParamValid
@GetMapping("path/{isInt}/{isString}")
public ResponseVO pathGet(@PathVariable @ParameterValid(type = Integer.class, msg = "isInt must be more than 2", isMin = true, min = 2) Integer isInt, @PathVariable @ParameterValid(type = String.class, msg = "isString is empty") String isString) {
    log.info("int:" + isInt);
    log.info("String:" + isString);
    JSONObject resultJson = new JSONObject();
    resultJson.put("isInt", isInt);
    resultJson.put("isString", isString);
    return new ResponseVO(HttpStatus.OK.value(), "pathGet", resultJson);
}
@GetMapping("query")
@PathAndQueryParamValid
public ResponseVO queryGet(@RequestParam @ParameterValid(type = Integer.class, msg = "isInt must be more than 2 ", isMin = true, min = 2) Integer isInt, @RequestParam @ParameterValid(type = String.class, msg = "isString is empty") String isString) {
   log.info("int:" + isInt);
   log.info("String:" + isString);
   JSONObject resultJson = new JSONObject();
   resultJson.put("isInt", isInt);
   resultJson.put("isString", isString);
   return new ResponseVO(HttpStatus.OK.value(), "queryGet", resultJson);
}
複製代碼

2.2 自定義註解(annotation)

2.2.1 @PathAndQueryParamValid

只是簡單的用於方法類型註解:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public  @interface  PathAndQueryParamValid {
}
複製代碼

2.2.1 @ParameterValid

@ParameterValid 能夠根據實際業務需求添加屬於你的校驗規則:

@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface ParameterValid {
    Class<?> type();

    String msg();

    boolean request() default true;

    boolean isEmpty() default true;

    boolean isBlank() default true;

    boolean isNull() default false;

    int min() default 0;
    int max() default 0;
    int[] section() default {0,0};
    boolean isMin() default false;
    boolean isMax() default false;
    boolean isSection() default false;
}
複製代碼

2.3 AOP切面(重點-1)

  • 經過joinPoint獲取切點方法名以及類名,後續(重點)有大用
  • 經過JoinPoint獲取方法的參數
  • 調用(重點2)ParamValidSupport
  • AdvanceResponseSupport和上一篇文章內容同樣,其實就是響應而已。
@Aspect
@Component
public class PathAndQueryParamValidAspect {

  private static final Logger log = LoggerFactory.getLogger(PathAndQueryParamValidAspect.class);

  @Before("@annotation(paramValid)")
  public void paramValid(JoinPoint joinPoint, PathAndQueryParamValid paramValid) {
      String className = joinPoint.getTarget().getClass().getName();
      String methodName = joinPoint.getSignature().getName();
      Object[] param = joinPoint.getArgs();
      try {
          List<String> errorLists = ParamValidSupport.get().validate(className, methodName,
                  ParameterValid.class, param);
          if (errorLists != null) {
              AdvanceResponseSupport.advanceResponse(
                      new ResponseVO(HttpStatus.BAD_REQUEST.value(), "parameter empty", errorLists));
          }
      } catch (NotFoundException | NoSuchMethodException | ClassNotFoundException e) {
          log.error("e-name:" + e.getClass().getName() + ": message:" + e.getMessage());
      }
  }
}
複製代碼

2.4 校驗(重點-2)

  • 經過方法名和類名,根據ClassPool獲取CtClass和CtMethod
  • 從而獲取參數註解,解析參數註解規則進行校驗參數

(這裏還能夠重構的,只是對int和string兩種類型進行校驗,還能夠添加其餘需求。把主要內容先呈現出來)

public class ParamValidSupport {
private static final Logger logger = LoggerFactory.getLogger(ParamValidSupport.class);

private static final String PARAM_TYPE_ERROR = "param type error";
private static final String INT_PARAM_ERROR = "Invalid interva";
private static final int INT_PARAM_TYPE_MAX_SIZE = 2;
private static final int INT_PARAM_SIZE_SUBSCRIPT_MIN = 0;
private static final int INT_PARAM_SIZE_SUBSCRIPT_MAX = 0;

private static final int STRING_SIZE = 2;
private static final char STRING_TYPE_END = '}';
private static final char STRING_TYPE_BEGIN = '{';
private static final char STRING_EMPTY_DOUBLE_CHARACTER = '"';
private static final char STRING_EMPTY_SINGLE_CHARACTER = '\'';

private static ParamValidSupport mInstance;

private ParamValidSupport() {
}

public static ParamValidSupport get() {
    if (mInstance == null) {
        synchronized (ParamValidSupport.class) {
            if (mInstance == null) {
                mInstance = new ParamValidSupport();
            }
        }
    }
    return mInstance;
}

 /** * 校驗 */
public List<String> validate(String className, String methodName, Class<?> annotationClass, Object[] args) throws NotFoundException, NoSuchMethodException, ClassNotFoundException {

    if (StringUtils.isBlank(className)) {
        return null;
    }
    if (StringUtils.isBlank(methodName)) {
        return null;
    }
    if (annotationClass == null) {
        return null;
    }

    ClassPool pool = ClassPool.getDefault();
    CtClass ct = pool.get(className);
    CtMethod ctMethod = ct.getDeclaredMethod(methodName);
    Object[][] parameterAnnotations = ctMethod.getParameterAnnotations();

    List<String> errorLists = new ArrayList<>();

    for (int i = 0; i < parameterAnnotations.length; i++) {
        Object[] parameterAnnotation = parameterAnnotations[i];
        Object param = args[i];
        for (Object object : parameterAnnotation) {
            Annotation annotation = (Annotation) object;
            Class<? extends Annotation> aClass = annotation.annotationType();
            if (aClass.equals(annotationClass)) {
                boolean isEmpty = ((ParameterValid) object).isEmpty();
                if (isEmpty) {
                    ParameterValid parameterValid = (ParameterValid) object;
                    String errorMsg = parameterValid.msg();
                    if (Integer.class.isAssignableFrom(param.getClass())){
                        int paramInt = (int) param;
                        if (parameterValid.isMin() && paramInt < parameterValid.min()) {
                            errorLists.add(errorMsg);
                        }
                        if (parameterValid.isMax() && paramInt < parameterValid.max()) {
                            errorLists.add(errorMsg);
                        }
                        if (parameterValid.isSection()) {
                            int[] section = parameterValid.section();
                            if (section.length != INT_PARAM_TYPE_MAX_SIZE) {
                                logger.error(INT_PARAM_ERROR);
                                throw new ParameterValidException(INT_PARAM_ERROR);
                            }
                            if (!(paramInt > section[INT_PARAM_SIZE_SUBSCRIPT_MIN] && paramInt < section[INT_PARAM_SIZE_SUBSCRIPT_MAX])) {
                                errorLists.add(errorMsg);
                            } else if (!(paramInt > section[INT_PARAM_SIZE_SUBSCRIPT_MAX] && paramInt < section[INT_PARAM_SIZE_SUBSCRIPT_MIN])) {
                                errorLists.add(errorMsg);
                            }
                        }
                    }

                    if (String.class.isAssignableFrom(param.getClass())){
                        String paramStr = (String) param;
                        if (parameterValid.isNull()) {
                            if (StringUtils.isEmpty(paramStr)) {
                                errorLists.add(errorMsg);
                            }
                        } else {
                            if (parameterValid.isBlank()) {
                                if (StringUtils.isBlank(paramStr)) {
                                    errorLists.add(errorMsg);
                                } else {
                                    int length = paramStr.length();
                                    char begin = paramStr.charAt(0);
                                    char end = paramStr.charAt(length - 1);
                                    if (STRING_TYPE_BEGIN == begin &&
                                            STRING_TYPE_END == end) {
                                        errorLists.add(errorMsg);
                                    }
                                    if (length == STRING_SIZE && STRING_EMPTY_DOUBLE_CHARACTER == begin
                                            && STRING_EMPTY_DOUBLE_CHARACTER == end) {
                                        errorLists.add(errorMsg);
                                    }
                                    if (length == STRING_SIZE && STRING_EMPTY_SINGLE_CHARACTER == begin
                                            && STRING_EMPTY_SINGLE_CHARACTER == end) {
                                        errorLists.add(errorMsg);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (errorLists.size() != 0) {
        return errorLists;
    }
    return null;
}
}
複製代碼

2.4 測試結果

測試結果1

測試結果2

測試結果3

測試結果4
相關文章
相關標籤/搜索