7

我想使用注释验证GET/POST请求 spring-boot 控制器类。javax.validation-api

对于类@Valid@NotBlank该类的属性可以完美地工作。

以下按预期工作:

public class Registration {
    @NotBlank
    private String name;
}

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

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

这可能吗?

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

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

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


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

在使用 POST 启动项目调用localhost:8080/registration?test=后,例如使用 Postman。参数“test”将为空,但@NotBlank仍会输入方法。

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

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

构建.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')
}
4

1 回答 1

3

你用 注释你的类@Validated吗?

例如:

@Validated
public class Controller {

   public ResponseEntity registration(@Valid @NotBlank String password) {}
}
于 2018-08-28T13:03:42.770 回答