JSR303
SpringMVC支持使用JSR303进行快速校验,我们只需要给需要校验的bean加上响应的校验注解即可
使用步骤:
- 给Controller方法参数对象加上校验注解
- 加上@Valid声明需要校验
- 咱需要检验的参数后面紧跟一个BindingResult,即可获取到校验结果
- 判断校验结果是否出错,进一步来决定业务逻辑
基于AOP统一校验
1、基于AOP方式,统一获取校验错误并封装返回
@Aspect
@Component
@Order(2)
public class BindingResultAspect {
@Pointcut("execution(public * com.gmall.controller.*.*(..))")
public void BindingResult() {
}
@Around("BindingResult()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
if (arg instanceof BindingResult) {
BindingResult result = (BindingResult) arg;
if (result.hasErrors()) {
return new CommonResult().validateFailed(result);
}
}
}
return joinPoint.proceed();
}
}
2、自定义校验注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER})
@Constraint(validatedBy = FlagValidatorClass.class)
public @interface FlagValidator {
String[] value() default {};
String message() default "flag is not found";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
3、自定义校验注解解析器
public class FlagValidatorClass implements ConstraintValidator<FlagValidator,Integer> {
private String[] values;
@Override
public void initialize(FlagValidator flagValidator) {
this.values = flagValidator.value();
}
@Override
public boolean isValid(Integer value,
ConstraintValidatorContext constraintValidatorContext) {
boolean isValid = false;
if(value==null){
//当状态为空时使用默认值
return true;
}
for(int i=0;i<values.length;i++){
if(values[i].equals(String.valueOf(value))){
isValid = true;
break;
}
}
return isValid;
}
}
网友评论