我想使用GET
批注验证POST
/ javax.validation-api
对spring-boot控制器类的请求。
对于类@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(例如Postman)启动项目后localhost:8080/registration?test=
进行调用。参数“ 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')
}
答案 0 :(得分:1)
您是否用@Validated
注释了班级?
例如:
@Validated
public class Controller {
public ResponseEntity registration(@Valid @NotBlank String password) {}
}