首頁 >Java >java教程 >SpringBoot怎麼使用validation做參數校驗

SpringBoot怎麼使用validation做參數校驗

WBOY
WBOY轉載
2023-05-21 11:10:101356瀏覽

    1.新增依賴

    #直接加入 hibernate-validator

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

    新增spring-boot-starter-validation

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-validation</artifactId>
                <version>1.4.0.RELEASE</version>
            </dependency>

    新增spring-boot-starter-web

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>

    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<String> 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<String> 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<String> 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做參數校驗的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除