How to solve the problem that Spring in action @ valid authentication is not effective

  • 2021-09-11 20:31:40
  • OfStack

Resolve that Spring in action @ valid validation is not effective

According to the sample code in the book, however, verification was added but did not take effect.

Spring provides verification that Api uses but does not provide an implementation, so you need to import your own implementation package.

So import the implementation package:


<dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.1.1.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>

However, the problem has not been solved, the program runs normally, and the verification does not take effect.

When I think of using Maven to import some jar reports before, I still can't find them (I don't know if it's because of the tomcat that comes with Xampp). The previous solution was to drop the Jar packet into the lib folder of Tomcat.

So I dropped two jar packages downloaded from Maven above, and there were some changes. This time, an error was reported, and the program could not run normally.

Error reporting:

Hibernate Validator java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl

Then look for a solution, found a solution on Stack Overflow, missing org. jboss. logging and com. fasterxml classmate packages, so add in Maven


  <dependency>
    <groupId>org.jboss.logging</groupId>
      <artifactId>jboss-logging</artifactId>
      <version>3.3.2.Final</version>
  </dependency>
  <dependency>
      <groupId>com.fasterxml</groupId>
      <artifactId>classmate</artifactId>
      <version>1.3.4</version>
  </dependency>

However, there is still no solution to the problem. Using the old method, throw these two Jar packets into the lib folder of Tomcat, and the problem is solved.

Recently encountered a lot of Maven imported package in the run time does not take effect, that is, do not report error, but run time nodefClass error.

Find a solution: Solve the problem that jar package is missing in idea import maven project

Why springboot @ Validate does not work

The problem of using validate related annotations but not taking effect


public class LoginRequest implements Serializable {
    private static final long serialVersionUID = 1L;
    @ApiModelProperty(value = " Mobile phone number ", required = true, example = "18888888")
    @Pattern(regexp = RegularConstants.PHONE, message = " Wrong format of mobile phone number ")
    @JsonProperty(value = "phone")
    private String phone;
    @ApiModelProperty(value = " Password ", required = true, example = "1~[6,18]")
    @Pattern(regexp = RegularConstants.PASSWORD, message = " The password is in the wrong format. The password must start with a letter and be in the length of 6~18 Can only contain characters, numbers, and underscores ")
    private String password;
}

Solutions

Introducing hibernate-related dependencies


       <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.21.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
        </dependency>

Related configuration


@Configuration
public class ValidatorConfiguration {
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .addProperty("hibernate.validator.fail_fast", "true")
                .buildValidatorFactory();
        return validatorFactory.getValidator();
    }
}

Global interception validation error


@RestControllerAdvice
public class WebGlobalExceptionHandler {
//    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     *  Intercept JSON Parameter check 
     */
//    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult bindException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        return CommonResult.failed(ExceptionCodeEnum.VALIDATE_FAILED,Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }
}

Related articles: