首页 > 技术文章 > SpringBoot 整合Validator统一参数校验

ruhuanxingyun 2019-05-08 14:54 原文

1. JSP303定义的校验类型

空检查

@Null       验证对象是否为null

@NotNull    验证对象是否不为null, 无法查检长度为0的字符串

@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.

@NotEmpty 检查约束元素是否为NULL或者是EMPTY.

 
Booelan检查

@AssertTrue     验证 Boolean 对象是否为 true  

@AssertFalse    验证 Boolean 对象是否为 false  

 
长度检查

@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  

@Length(min=, max=) Validates that the annotated string is between min and max included.

 
日期检查

@Past           验证 Date 和 Calendar 对象是否在当前时间之前  

@Future     验证 Date 和 Calendar 对象是否在当前时间之后  

@Pattern    验证 String 对象是否符合正则表达式的规则
 

数值检查,建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null

@Min            验证 Number 和 String 对象是否大等于指定的值  

@Max            验证 Number 和 String 对象是否小等于指定的值  

@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度

@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度

@Digits     验证 Number 和 String 的构成是否合法  

@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。

@Range(min=, max=) Checks whether the annotated value lies between (inclusive) the specified minimum and maximum.

@Range(min=10000,max=50000,message="range.bean.wage")
private BigDecimal wage;

@Valid 递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)

@CreditCardNumber信用卡验证

@Email  验证是否是邮件地址,如果为null,不进行验证,算通过验证。

@ScriptAssert(lang= ,script=, alias=)

@URL(protocol=,host=, port=,regexp=, flags=)

 

2. @RequestParam参数校验

  A. 方法所在的控制层Controller上加@Validated注解;

  B. 请求方法Method上加上需要校验的注解,比如:@Size等,最好重写message属性;

  C. 捕捉校验失败异常信息:ConstraintViolationException异常

  例如:

package com.ruhuanxingyun.controller;

import com.ruhuanxingyun.controller.response.JsonResult;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ErrorHandlerController {
    
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JsonResult handleBindException(BindException e) {
        // 得到第一个字段的错误信息
        String msg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        
        return JsonResult.error(msg);
    }

}

 

3. 实体对象参数校验

  A. 实体类字段上加需要校验的注解;

       B. 请求方法上实体前加@Valid或@Validated注解,对入参实体进行嵌套验证必须在响应字段上加@Valid,而不是@Validated;

  C. 捕捉校验失败异常信息:BindException异常,或者在实体后使用BindingResult类,然后进行处理;

  D. 分组校验,还可以排序,例如:新增和修改,参数ID有无的问题。

  例如:

package com.ruhuanxingyun.controller;

import com.ruhuanxingyun.controller.response.JsonResult;import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

@ControllerAdvice
public class ErrorHandlerController {
   
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public JsonResult handleValidationException(ConstraintViolationException e) {
        // 得到第一个字段的错误信息
        String msg = e.getConstraintViolations().iterator().next().getMessage();

        return JsonResult.error(msg);
    }

}

 

4. 检测第一个失败就抛出异常,配置如下:

@Configuration
public class WebConfig {
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                //failFast的意思只要出现校验失败的情况,就立即结束校验,不再进行后续的校验。
                .failFast(true)
                .buildValidatorFactory();

        return validatorFactory.getValidator();
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator(validator());
        return methodValidationPostProcessor;
    }
}

 

可参考:springboot使用hibernate validator校验

推荐阅读