[英]How do I use @NotEmpty constraint to validate an HTTP request body in Spring Boot?
我有一个包含 HTTP 端点的 RestController 来创建新用户。
@RestController
public class UserController {
@PostMapping("/user")
public CompletableFuture<ResponseEntity<UserResponse>> createUser(
@Valid @RequestBody UserRequest userRequest) {
return CompletableFuture.completedFuture(
ResponseEntity.status(HttpStatus.ACCEPTED).body(userService.createUser(userRequest)));
}
}
我的UserRequest model如下:
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(NON_NULL)
@NoArgsConstructor
public class UserRequest {
// @NotNull
@NotEmpty private String name;
}
现在,每次我使用有效负载(例如{ "name": "John" }
)调用 POST /user 端点时,我都会收到以下错误:
HV000030: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.String'. Check configuration for 'name'"
换句话说,无论“name”属性是否为空,都会抛出异常。
但是,当我改为使用@NotNull
约束时,仅在没有 name 属性或{ "name": null }
的情况下才会抛出异常,正如预期的那样。
我是否滥用了 @NotEmpty 约束?
对于验证字符串的变量,您应该使用@NotBlank
此约束检查 null 和字符串变量的空白值(例如“”或“”)或@NotNull
如果您想检查唯一的可为空值
@NotEmpty
用于 Collection 的类型检查。
检查此以获取更多信息: https://www.baeldung.com/java-bean-validation-not-null-empty-blank
Maven 依赖项(在 pom.xml 中)-
<!-- Java bean validation API - Spec -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- Hibernate validator - Bean validation API Implementation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.11.Final</version>
</dependency>
<!-- Verify validation annotations usage at compile time -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>6.0.11.Final</version>
</dependency>
在用户请求模型中-
import javax.validation.constraints.NotEmpty;
@NotEmpty(message = "Name cannot be empty")
private String name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.