如何直接使用 javax 验证简单字符串参数的@NotBlank?

How to validate @NotBlank for simple string parameter directly with javax?

我想用 javax.validation-api 注释验证 GET / POST 对 spring-引导控制器 class 的请求。

对于 classes @Valid@NotBlank 对于 class 的属性工作得很好。

以下按预期工作:

public class Registration {
    @NotBlank
    private String name;
}

public ResponseEntity registration(@Valid @RequestBody Registration registration) {}

所以现在我只有一个字符串作为参数并想验证它。

这可能吗?

以下未按预期工作(未验证任何内容):

public ResponseEntity registration(@Valid @NotBlank String password) {}

这似乎是一个简单的要求,但我在互联网或 Whosebug 上找不到任何东西。


为了复制,我创建了一个 MWE(java 10,gradle 项目):

启动项目后,使用 POST 调用 localhost:8080/registration?test=,例如使用 Postman。参数 "test" 将为空,但将输入尽管 @NotBlank 的方法。

localhost:8080/container 的 POST 调用按预期失败。

MweController.java

import javax.validation.constraints.*;

import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

@RestController
public class MweController {

    @CrossOrigin(origins = "http://localhost:3000")
    @PostMapping(value = "/registration")
    public ResponseEntity registration(@NotNull @NotBlank @NotEmpty String test) {
        System.out.println("Parameter: " + test);
        // This should return Bad Request but doesn't!
        return new ResponseEntity(HttpStatus.OK);
    }

    @CrossOrigin(origins = "http://localhost:3000")
    @PostMapping(value = "/container")
    public ResponseEntity container(@Valid Container test) {
        System.out.println("Parameter: " + test);
        // This returns Bad Request as expected
        return new ResponseEntity(HttpStatus.OK);
    }

    class Container {
        public Container(String test){
            this.test = test;
        }

        @NotBlank
        private String test;
    }

}

MweApplication.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MweApplication {

    public static void main(String[] args) {
        SpringApplication.run(MweApplication.class, args);
    }
}

build.gradle

buildscript {
    ext {
        springBootVersion = '2.1.0.M2'
    }
    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.mwe'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 10

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
}


dependencies {
    compile('org.springframework.boot:spring-boot-starter-webflux')
}

你用 @Validated 注释了你的 class 了吗?

例如:

@Validated
public class Controller {

   public ResponseEntity registration(@Valid @NotBlank String password) {}
}