我正在尝试验证由@Validated 注释的@RestController 中由@Valid 注释注释的简单请求正文。验证在请求中的原始变量上正常工作(在下面的示例中是年龄),但不适用于 pojo 请求正文。@Valid 注释对请求主体 Person 类没有影响(即控制器接受空白姓名和 18 岁以下的年龄)。
人物类:
import javax.validation.constraints.Min
import javax.validation.constraints.NotBlank
class Person (
@NotBlank
val name : String,
@Min(18)
val age : Int
)
Run Code Online (Sandbox Code Playgroud)
控制器类:
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import javax.validation.Valid
@RestController
@Validated
class HomeController {
@GetMapping("/{age}")
fun verifyAge(@PathVariable("age") @Min(18) age:Int): String {
return "Eligible age."
}
@PostMapping
fun personValidation(@Valid @RequestBody person : Person) : String {
return "No validation error"
}
}
Run Code Online (Sandbox Code Playgroud)
@NotBlank、@Min 和 @Valid 注释来自以下依赖项:
implementation("org.springframework.boot:spring-boot-starter-validation:2.3.0.RELEASE")
Run Code Online (Sandbox Code Playgroud)
如何使@Valid 在@Validated …
以下代码不会抛出任何错误,它是一个独立的java程序.相反,如果我传递null,它将在控制台中打印null.请帮帮我,如何启用@notnull注释.
import javax.validation.constraints.NotNull;
public class TestNotNull {
public void testNotNull(@NotNull(message = "name is compulsory") String name)
{
System.out.println(name);
}
public static void main(String... args)
{
TestNotNull testNotNull = new TestNotNull();
testNotNull.testNotNull(null);
}
}
Run Code Online (Sandbox Code Playgroud)