简体   繁体   English

Spring 引导验证注释 @Valid 和 @NotBlank 不工作

[英]Spring boot validation annotations @Valid and @NotBlank not working

Given below is my main controller from which I am calling the getPDFDetails method.下面给出的是我的主要 controller,我从中调用getPDFDetails方法。

@RequestMapping(value=PATH_PRINT_CONTRACTS, method=RequestMethod.POST)
    public ResponseEntity<?> printContracts(@RequestBody final UpdatePrintContracts updatePrintContracts) throws Exception {
    
        System.out.println("contracts value is "+ updatePrintContracts);
        
        Integer cancellationReasons = service.getPDFDetails(updatePrintContracts);
        
        System.out.println("success!");
        
        return ResponseEntity.ok(cancellationReasons);
    }   

Below is the UpdatePrintContracts class where I have defined all the variables with validation annotations and corresponding getter/setter methods.下面是UpdatePrintContracts class,我在其中定义了所有带有验证注释和相应的 getter/setter 方法的变量。

public class UpdatePrintContracts {
    
    @Valid
    @NotBlank
    @Pattern(regexp = "\\p{Alnum}{1,30}")
    String isReprint;
    
    @Valid
    @NotBlank
    Integer dealerId;
    
    @Valid
    @NotBlank
    @Pattern(regexp = "\\p{Alnum}{1,30}")
    String includeSignatureCoordinates;
    
    @Valid
    @NotBlank
    java.util.List<Integer> contractNumbers;

    public String getIsReprint() {
        return isReprint;
    }

    public void setIsReprint(String isReprint) {
        this.isReprint = isReprint;
    }

    public Integer getDealerId() {
        return dealerId;
    }

    public void setDealerId(Integer dealerId) {
        this.dealerId = dealerId;
    }

    public String getIncludeSignatureCoordinates() {
        return includeSignatureCoordinates;
    }

    public void setIncludeSignatureCoordinates(String includeSignatureCoordinates) {
        this.includeSignatureCoordinates = includeSignatureCoordinates;
    }

    public java.util.List<Integer> getContractNumbers() {
        return contractNumbers;
    }

    public void setContractNumbers(java.util.List<Integer> contractNumbers) {
        this.contractNumbers = contractNumbers;
    }
    
}

I am trying to run the application as a Spring Boot app by right clicking on the project (Run As) and passing blank values for variables isReprint and includeSignatureCoordinates through Soap UI.我试图通过右键单击项目(运行方式)并通过 Soap UI 传递变量isReprintincludeSignatureCoordinates的空白值,将应用程序作为 Spring 启动应用程序运行。 However the validation doesn't seem to work and is not throwing any validation error in Soap UI.但是,验证似乎不起作用,并且不会在 Soap UI 中抛出任何验证错误。 What am I missing?我错过了什么? Any help is appreciated!任何帮助表示赞赏!

If you are facing this problem in latest version of spring boot (2.3.0) make sure to add the following dependency:如果您在最新版本的 spring boot (2.3.0) 中遇到此问题,请确保添加以下依赖项:

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

Observation: In earlier version of Spring Boot (1.4.7), javax.validation used to work out of the box.观察:在早期版本的 Spring Boot (1.4.7) 中, javax.validation曾经是开箱即用的。 But, after upgrading to latest version, annotations broke.但是,升级到最新版本后,注释坏了。 Adding the following dependency alone doesn't work:单独添加以下依赖项不起作用:

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
</dependency>

Because this provides JSR Specification but not the implementation.因为这提供了 JSR 规范而不是实现。 You can also use hibernate-validator instead of spring-boot-starter-validation .您还可以使用hibernate-validator而不是spring-boot-starter-validation

For Anyone who is getting this issue with 2.0.1.Final :对于在2.0.1.Final 中遇到此问题的任何人:

In all SpringBoot versions above 2.2, Validations starter is not a part of web starter anymore在 2.2 以上的所有 SpringBoot 版本中, Validations starter 不再是 web starter 的一部分

Check Notes here 在此处检查注释

So, all you have to do is add this dependency in your build.gradle/pom file所以,你所要做的就是在你的 build.gradle/pom 文件中添加这个依赖项

GRADLE:等级:

implementation 'org.springframework.boot:spring-boot-starter-validation'

MAVEN行家

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

First you dont need to have @Valid annotation for those class variables in UpdatePrintContracts .首先,您不需要为 UpdatePrintContracts 中的那些类变量添加 @Valid 注释。 You can delete them.您可以删除它们。

To trigger validation of a @Controller input, simply annotate the input argument as @Valid or @Validated:要触发 @Controller 输入的验证,只需将输入参数注释为 @Valid 或 @Validated:

@RequestMapping(value=PATH_PRINT_CONTRACTS, method=RequestMethod.POST)
public ResponseEntity<?> printContracts(@Valid @RequestBody  final UpdatePrintContracts updatePrintContracts) throws Exception {

Refer here for full understanding of validating models in spring boot.请参阅此处以全面了解 Spring Boot 中的验证模型。

And If you want to check that a string contains only specific characters, you must add anchors (^ for beginning of the string, $ for end of the string) to be sure that your pattern matches all the string.Curly brackets are only to write a quantity,如果你想检查一个字符串是否只包含特定的字符,你必须添加锚点(^ 表示字符串的开头,$ 表示字符串的结尾)以确保你的模式匹配所有字符串。大括号只写一个数量,

@Pattern(regexp = "^[\\p{Alnum}]{1,32}$")

Lastly i assume you have following jars in your classpath,最后,我假设您的类路径中有以下 jars,

.validation-api.jar (contains the abstract API and the annotation scanner) .validation-api.jar(包含抽象API和注解扫描器)

.hibernate-validator.jar (contains the concrete implementation) .hibernate-validator.jar(包含具体实现)

I was using This dependency of validation in spring boot and didn't work ,我在 spring boot 中使用了这种验证依赖,但没有用,

<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>

I replaced it with spring-boot-starter-validation and it worked .我用 spring-boot-starter-validation 替换了它并且它起作用了。

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot- 
starter-validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.4.0</version>

My problem solved by this.我的问题由此解决。 When we use classes inside classes that also need validations so @Valid needs to be annotated to all in that case.当我们在类中使用也需要验证的类时,在这种情况下需要将@Valid注释给所有类。 Link for more details 链接了解更多详情

this is for anyone here who still has the same issue after following the steps mentioned above.这适用于在执行上述步骤后仍然遇到相同问题的任何人。 I had to restart my IDE (IntelliJ) for the changes to take effect.我必须重新启动我的 IDE (IntelliJ) 才能使更改生效。

I faced the same error.我遇到了同样的错误。

I had to use the below 2 dependencies alone:我不得不单独使用以下 2 个依赖项:

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

And use @Validated annotation(import org.springframework.validation.annotation.Validated) on rest controller level and @Valid annotation at method argument level(import javax.validation.Valid)并在其余控制器级别使用@Validated annotation(import org.springframework.validation.annotation.Validated) 并在方法参数级别使用@Valid annotation(import javax.validation.Valid)

If there are any other extra dependencies like javax.validation.validation-api , org.hibernate.hibernate-validator , etc then the validations stopped working for me.如果有任何其他额外的依赖项,如javax.validation.validation-apiorg.hibernate.hibernate-validator等,那么验证对我来说就停止工作了。 So make sure that you remove these dependencies from pom.xml因此,请确保从 pom.xml 中删除这些依赖项

You have to add this dependency in pom.xml您必须在 pom.xml 中添加此依赖项

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

Step-1: Add these two dependency in the pom.xml file Step-1:在pom.xml文件中添加这两个依赖

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>

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

Step-2: Create a Custom Exception class like this第 2 步:像这样创建自定义异常 class

package com.bjit.salon.auth.service.exceptions;


import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

@ControllerAdvice
public class AnynameApplicationException {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<List<String>> processUnmergeException(final 
MethodArgumentNotValidException ex) {

        List<String> list = ex.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());

        return new ResponseEntity<>(list, HttpStatus.BAD_REQUEST);
    }
}

Step-3: Add @Valid annotation to the method arguments like this way Step-3:像这样在方法arguments中添加@Valid注解

public ResponseEntity<?> registerAccount(@Valid @RequestBody UserRegisterDto 
      registerDto) {
       
    // rest of the codes
}

Make sure to use @Valid annotation before @RequestBody确保在@RequestBody 之前使用@Valid 注解

For newer versions of spring boot ensure all validation annotation are picked from jakarta.validation.* package and not javax.validation.* .对于较新版本的 spring 引导,确保所有验证注释均来自jakarta.validation.* package 而不是javax.validation.* As the annotations are named same in both.由于注释在两者中的名称相同。

You can use @NotEmpty will check for both blank and null values.您可以使用 @NotEmpty 来检查空白值和 null 值。 Add @Valid to your RestContoller class methods将 @Valid 添加到您的 RestContoller class 方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM