SpringBoot使用validation做参数校验说明

1.添加依赖

直接添加 hibernate-validator


            org.hibernate.validator
            hibernate-validator
            6.0.2.Final
        

添加spring-boot-starter-validation


            org.springframework.boot
            spring-boot-starter-validation
            1.4.0.RELEASE
        

添加spring-boot-starter-web


            org.springframework.boot
            spring-boot-starter-web
        

2. 配置文件

如果想要设置fail_fast属性的话,true表示有一个参数出错即返回,默认的时检验所有的参数,那么必须要有配置文件

import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
/**
 * hibernate参数验证配置
 */
@Configuration
public class ValidatorConfig extends WebMvcConfigurerAdapter {


    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                // 将fail_fast设置为true即可,如果想验证全部,则设置为false或者取消配置即可
                .failFast(true)
//                .addProperty("hibernate.validator.fail_fast", "true")
                .buildValidatorFactory();

        return validatorFactory.getValidator();
    }

    /**
     * requestParam方式的校验
     * @return
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {

        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator(validator());
        return methodValidationPostProcessor;
    }
    @Override
    public org.springframework.validation.Validator getValidator() {
        return new SpringValidatorAdapter(validator());
    }
}

其中methodValidationPostProcessor是对requestParam起作用

继承WebMvcConfigurerAdapter 并且重写getValidator()方法,是让spring的请求校验Validator使用我们上边的validator,让设置的failFast生效,具体可参考org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#mvcValidator方法

3.统一异常处理

/**
     * hibernate-valid实体类形式接受参数验证失败
     * @param ex
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public WebResult validationErrorHandler(BindException ex) {
        List collect = ex.getBindingResult().getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        return new WebResult(Errors.INCORRECT_PARAM_FORMAT.getError(), StringUtils.join(collect, ";"));
    }

    /**
     * hibernate-valid实体类形式接受参数验证失败
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public WebResult validationErrorHandler(MethodArgumentNotValidException ex) {
        List collect = ex.getBindingResult().getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        return new WebResult(Errors.INCORRECT_PARAM_FORMAT.getError(), StringUtils.join(collect, ";"));

    }
    /**
     * RequestParam方式参数校验
     * @param ex
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public WebResult validationErrorHandler(ConstraintViolationException ex) {
        List errorInformation = ex.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());
        return new WebResult(Errors.INCORRECT_PARAM_FORMAT.getError(),StringUtils.join(errorInformation, ";"));
    }

4.使用

如果是@RequestParam这样直接写参数校验的话,在类上或者对应方法上加上Validated注解,如果是实体类接受的话,在参数中的实体前加上@Valid即可

到此这篇关于SpringBoot使用validation做参数校验说明的文章就介绍到这了,更多相关SpringBoot参数校验内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(SpringBoot使用validation做参数校验说明)