【无标题】

Java API规范 (JSR303) 定义了Bean校验的标准validation-api,但没有提供实现。hibernate validation是对这个规范的实现,并增加了校验注解如@Email、@Length等。

1 引入依赖

<dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-validator</artifactId>
     <version>6.0.1.Final</version>
</dependency>

2 参数校验

对于web服务来说,为防止非法参数对业务造成影响,在Controller层一定要做参数校验的!大部分情况下,请求参数分为如下两种形式:
1,POST、PUT请求,使用requestBody传递参数;
2,GET请求,使用requestParam/PathVariable传递参数。
下面我们简单介绍下requestBody和requestParam/PathVariable的参数校验实战!

requestBody参数校验

POST、PUT请求一般会使用requestBody传递参数,这种情况下,后端使用** DTO 对象进行接收。
只要给 DTO 对象加上@Validated注解就能实现自动参数校验**。
比如,有一个保存User的接口,要求userName长度是2-10,account和password字段长度是6-20。
如果校验失败,会抛出MethodArgumentNotValidException异常,
Spring默认会将其转为400(Bad Request)请求。

DTO 表示数据传输对象(Data Transfer Object),用于服务器和客户端之间交互传输使用的。
在 spring-web 项目中可以表示用于接收请求参数的Bean对象。

在DTO字段上声明约束注解

@Data
public class UserDTO {
    private Long userId;
    @NotNull      @Length(min = 2, max = 10)
    private String userName;

    @NotNull      @Length(min = 6, max = 20)
    private String account;

    @NotNull      @Length(min = 6, max = 20)
    private String password;
}

在方法参数上声明校验注解

@PostMapping("/save")
public Result saveUser(@RequestBody @Validated UserDTO userDTO) {
    return Result.ok();
}

这种情况下,使用@Valid和@Validated都可以。

requestParam/PathVariable参数校验
GET请求一般会使用requestParam/PathVariable传参。
如果参数比较多 (比如超过 6 个),还是推荐使用DTO对象接收。否则,推荐将一个个参数平铺到方法入参中。
在这种情况下,必须在Controller类上标注@Validated注解,并在入参上声明约束注解 (如@Min等)
如果校验失败,会抛出ConstraintViolationException异常。代码示例如下:

@RequestMapping("/api/user")
 @RestController
 @Validated
 public class UserController {

     @GetMapping("{userId}")
     public Result detail(@PathVariable("userId") @Min(10000000000000000L) Long userId) {
         UserDTO userDTO = new UserDTO();
         userDTO.setUserId(userId);
         userDTO.setAccount("11111111111111111");
         userDTO.setUserName("xixi");
         userDTO.setAccount("11111111111111111");
         return Result.ok(userDTO);
     }

     @GetMapping("getByAccount")
     public Result getByAccount(@Length(min = 6, max = 20) @NotNull String  account) {
         UserDTO userDTO = new UserDTO();
         userDTO.setUserId(10000000000000003L);
         userDTO.setAccount(account);
         userDTO.setUserName("xixi");
         userDTO.setAccount("11111111111111111");
         return Result.ok(userDTO);
     }
 }

统一异常处理
前面说过,如果校验失败,会抛出MethodArgumentNotValidException或者ConstraintViolationException异常。
在实际项目开发中,通常会用统一异常处理来返回一个更友好的提示。比如我们系统要求无论发送什么异常,http的状态码必须返回200,由业务码去区分系统的异常情况。

@RestControllerAdvice
public class CommonExceptionHandler {
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField())
            .append(":")
            .append(fieldError.getDefaultMessage())
            .append(", ");
        }
        String msg = sb.toString();
        return Result.fail(BusinessCode.参数校验失败, msg);
    }

    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result handleConstraintViolationException(ConstraintViolationException ex) {
        return Result.fail(BusinessCode.参数校验失败, ex.getMessage());
    }
 }

进阶使用 分组校验
在实际项目中,可能多个方法需要使用同一个DTO类来接收参数,而不同方法的校验规则很可能是不一样的。
这个时候,简单地在DTO类的字段上加约束注解无法解决这个问题。因此,spring-validation支持了分组校验的功能,专门用来解决这类问题。还是上面的例子,
比如保存User的时候,UserId是可空的,但是更新User的时候,UserId的值必须>=10000000000000000L;其它字段的校验规则在两种情况下一样。
这个时候使用分组校验的代码示例如下:

约束注解上声明适用的分组信息groups

 @Data
 public class UserDTO {
     @Min(value = 10000000000000000L, groups = Update.class)
     private Long userId;

     @NotNull(groups = {Save.class, Update.class})
     @Length(min = 2, max = 10, groups = {Save.class, Update.class})
     private String userName;        
 
     @NotNull(groups = {Save.class, Update.class})
     @Length(min = 6, max = 20, groups = {Save.class, Update.class})
     private String account;

     @NotNull(groups = {Save.class, Update.class})
     @Length(min = 6, max = 20, groups = {Save.class, Update.class})
     private String password;

     public interface Save {      }
     public interface Update {      }
 }

@Validated注解上指定校验分组

@PostMapping("/save")  
public Result saveUser(@RequestBody @Validated(UserDTO.Save.class) UserDTO userDTO) {        
    return Result.ok();  
}    
 
 @PostMapping("/update")  
 public Result updateUser(@RequestBody @Validated(UserDTO.Update.class) UserDTO userDTO) {
    return Result.ok();  
 }

嵌套校验
前面的示例中,DTO类里面的字段都是基本数据类型和String类型。但是实际场景中,有可能某个字段也是一个对象,这种情况先,可以使用嵌套校验。

比如,上面保存User信息的时候同时还带有Job信息。需要注意的是,此时DTO类的对应字段必须标记@Valid注解。

@Data  
public class UserDTO {
    @Min(value = 10000000000000000L, groups = Update.class)
    private Long userId; 

    @NotNull(groups = {Save.class, Update.class})
    @Length(min = 2, max = 10, groups = {Save.class, Update.class})
    private String userName;    

    @NotNull(groups = {Save.class, Update.class})
    @Length(min = 6, max = 20, groups = {Save.class, Update.class})
    private String account;  

    @NotNull(groups = {Save.class, Update.class})
    @Length(min = 6, max = 20, groups = {Save.class, Update.class})
    private String password;   

    @NotNull(groups = {Save.class, Update.class})
    @Valid      private Job job;        

@Data      
public static class Job {
    @Min(value = 1, groups = Update.class)          
    private Long jobId;

    @NotNull(groups = {Save.class, Update.class})
    @Length(min = 2, max = 10, groups = {Save.class, Update.class})          
    private String jobName;

    @NotNull(groups = {Save.class, Update.class})          
    @Length(min = 2, max = 10, groups = {Save.class, Update.class})
    private String position;      
}        
public interface Save {      }        
public interface Update {      }  
}

嵌套校验可以结合分组校验一起使用。还有就是嵌套集合校验会对集合里面的每一项都进行校验,例如List字段会对这个list里面的每一个Job对象都进行校验。

集合校验
如果请求体直接传递了json数组给后台,并希望对数组中的每一项都进行参数校验。此时,如果我们直接使用java.util.Collection下的list或者set来接收数据,
参数校验并不会生效!我们可以使用自定义list集合来接收参数:

包装List类型,并声明@Valid注解

public class ValidationList<E> implements List<E> {
    @Delegate
    @Valid
    public List<E> list = new ArrayList<>();

    @Override      
    public String toString() {
        return list.toString();      
    }  
}

@Delegate注解受lombok版本限制,1.18.6以上版本可支持。如果校验不通过,会抛出NotReadablePropertyException,同样可以使用统一异常进行处理。

比如,我们需要一次性保存多个User对象,Controller层的方法可以这么写:

@PostMapping("/saveList")  
public Result saveList(@RequestBody @Validated(UserDTO.Save.class) ValidationList<UserDTO> userList) { 
    return Result.ok();  
}

自定义校验
业务需求总是比框架提供的这些简单校验要复杂的多,我们可以自定义校验来满足我们的需求。自定义spring validation非常简单,假设我们自定义加密id
(由数字或者a-f的字母组成,32-256长度)校验,主要分为两步:

自定义约束注解

 @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
 @Retention(RUNTIME)  @Documented  @Constraint(validatedBy = {EncryptIdValidator.class})
 public @interface EncryptId {      
 String message() default "加密id格式错误";       
 Class<?>[] groups() default {};       
 Class<? extends Payload>[] payload() default {}; 
 }

实现ConstraintValidator接口编写约束校验器

public class EncryptIdValidator implements ConstraintValidator<EncryptId, String> {
    private static final Pattern PATTERN = Pattern.compile("^[a-f\\d]{32,256}$");
   
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
       if (value != null) {              
           Matcher matcher = PATTERN.matcher(value);
           return matcher.find();          
       }
       return true;      
      
 }

这样我们就可以使用@EncryptId进行参数校验了!

编程式校验
上面的示例都是基于注解来实现自动校验的,在某些情况下,我们可能希望以编程方式调用验证。这个时候可以注入javax.validation.Validator对象,然后再调用其api。

 @Autowired  private javax.validation.Validator globalValidator;
 @PostMapping("/saveWithCodingValidate")
 public Result saveWithCodingValidate(@RequestBody UserDTO userDTO) {
     Set<ConstraintViolation<UserDTO>> validate = globalValidator.validate(userDTO, UserDTO.Save.class);
     if (validate.isEmpty()) {   
 
     }else {
        for (ConstraintViolation<UserDTO> userDTOConstraintViolation : validate) {
        System.out.println(userDTOConstraintViolation);          
        }      
     }
     return Result.ok();  
 }

快速失败 (Fail Fast)
Spring Validation默认会校验完所有字段,然后才抛出异常。可以通过一些简单的配置,开启Fali Fast模式,一旦校验失败就立即返回。

@Bean  
public Validator validator() {
    ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
    .configure()                
    .failFast(true)
    .buildValidatorFactory();

    return validatorFactory.getValidator();  
}

@Valid和@Validated区别

实现原理
requestBody参数校验实现原理
在spring-mvc中,RequestResponseBodyMethodProcessor是用于解析@RequestBody标注的参数以及处理@ResponseBody标注方法的返回值的。
显然,执行参数校验的逻辑肯定就在解析参数的方法resolveArgument()中:

public class RequestResponseBodyMethodProcessor extends AbstractMessageConverterMethodProcessor {
 @Override      
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,                                    
NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {           
 parameter = parameter.nestedIfOptional();            
 Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());         
  String name = Conventions.getVariableNameForParameter(parameter);       
      if (binderFactory != null) {             
       WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);      
              if (arg != null) {                
                  validateIfApplicable(binder, parameter);                
                if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {             
                         throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());        
                     }              
                 }             
                 if (mavContainer != null) {             
                        mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());             
                         }        
                   }      
                   return adaptArgumentIfNecessary(arg, parameter);     
                        }  
               }

可以看到,resolveArgument()调用了validateIfApplicable()进行参数校验。

protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
    Annotation[] annotations = parameter.getParameterAnnotations();      for (Annotation ann : annotations) {
        Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
        if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) { 

            Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));         
            Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});       
            binder.validate(validationHints);             
            break;          
        }      
    }  
}

看到这里,大家应该能明白为什么这种场景下@Validated、@Valid两个注解可以混用。我们接下来继续看WebDataBinder.validate()实现。

@Override
public void validate(Object target, Errors errors, Object… validationHints) {
if (this.targetValidator != null) {
processConstraintViolations(
this.targetValidator.validate(target, asValidationGroups(validationHints)), errors);
}
}
最终发现底层最终还是调用了Hibernate Validator进行真正的校验处理。

方法级别的参数校验实现原理
上面提到的将参数一个个平铺到方法参数中,然后在每个参数前面声明约束注解的校验方式,就是方法级别的参数校验。实际上,这种方式可用于任何Spring Bean的方法上,
比如Controller/Service等。其底层实现原理就是AOP,具体来说是通过MethodValidationPostProcessor动态注册AOP切面,然后使用MethodValidationInterceptor
对切点方法织入增强。

public class MethodValidationPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessor implements InitializingBean {
    @Override      
    public void afterPropertiesSet() {
        Pointcut pointcut = new AnnotationMatchingPointcut(this.validatedAnnotationType, true);
        this.advisor = new DefaultPointcutAdvisor(pointcut, createMethodValidationAdvice(this.validator));      
    }

    protected Advice createMethodValidationAdvice(@Nullable Validator validator) {
    return (validator != null ? new MethodValidationInterceptor(validator) : new MethodValidationInterceptor());      
    }  
}

接着看一下MethodValidationInterceptor:

public class MethodValidationInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
if (isFactoryBeanMetadataMethod(invocation.getMethod())) {

        return invocation.proceed();          
    }
    Class<?>[] groups = determineValidationGroups(invocation);
    ExecutableValidator execVal = this.validator.forExecutables();
    Method methodToValidate = invocation.getMethod();
    Set<ConstraintViolation<Object>> result;          
    try {
        result = execVal.validateParameters(
        invocation.getThis(), methodToValidate, invocation.getArguments(), groups);          
    }
    catch (IllegalArgumentException ex) {             
    ...          
    }            
    if (!result.isEmpty()) {
        throw new ConstraintViolationException(result);          
    }            
    Object returnValue = invocation.proceed();
    result = execVal.validateReturnValue(invocation.getThis(), methodToValidate, returnValue, groups);
    if (!result.isEmpty()) {              
        throw new ConstraintViolationException(result);          
    }
    return returnValue;      
 }  

}
实际上,不管是requestBody参数校验还是方法级别的校验,最终都是调用Hibernate Validator执行校验,Spring Validation只是做了一层封装。
几乎涵盖你需要的SpringBoot所有操作
@Null 只能是null
@NotNull 不能为null 注意用在基本类型上无效,基本类型有默认初始值

@AssertFalse 必须为false
@AssertTrue 必须是true

字符串/数组/集合检查:(字符串本身就是个数组)
@Pattern(regexp=“reg”) 验证字符串满足正则
@Size(max, min) 验证字符串、数组、集合长度范围
@NotEmpty 验证字符串不为空或者null
@NotBlank 验证字符串不为null或者trim()后不为空

数值检查:同时能验证一个字符串是否是满足限制的数字的字符串
@Max 规定值得上限int
@Min 规定值得下限

@DecimalMax(“10.8”) 以传入字符串构建一个BigDecimal,规定值要小于这个值
@DecimalMin 可以用来限制浮点数大小

@Digits(int1, int2) 限制一个小数,整数精度小于int1;小数部分精度小于int2
@Digits 无参数,验证字符串是否合法
@Range(min=long1,max=long2) 检查数字是否在范围之间
这些都包括边界值

日期检查:Date/Calendar
@Post 限定一个日期,日期必须是过去的日期
@Future 限定一个日期,日期必须是未来的日期

其他验证:
@Vaild 递归验证,用于对象、数组和集合,会对对象的元素、数组的元素进行一一校验
@Email 用于验证一个字符串是否是一个合法的右键地址,空字符串或null算验证通过
@URL(protocol=,host=,port=,regexp=,flags=) 用于校验一个字符串是否是合法UR

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值