search
HomeJavajavaTutorialHow does SpringBoot use validation for parameter verification?

    1. Add dependencies

    Add hibernate-validator directly

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

    Add spring-boot-starter-validation

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

    Add spring-boot-starter-web

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

    2. Configuration file

    If you want to set the fail_fast attribute, true means there is If a parameter fails, it will be returned. By default, all parameters are tested, so there must be a configuration file

    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());
        }
    }

    The methodValidationPostProcessor works on requestParam

    Inheritance WebMvcConfigurerAdapter And rewrite the getValidator() method to let spring's request verification Validator use our validator above to make the set failFast take effect, For details, please refer to org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#mvcValidatorMethod

    3. Unified exception handling

    /**
         * 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.Use

    If @RequestParam is used to directly write parameter verification, add the Validated annotation to the class or corresponding method. If the entity class accepts it, add the Validated annotation to the parameter. Just add

    @Valid
    before the entity in ######

    The above is the detailed content of How does SpringBoot use validation for parameter verification?. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

    Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

    The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

    Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

    Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

    Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

    JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

    TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

    Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

    Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

    Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

    Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

    How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

    To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

    How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

    ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor