java - 如何在 Spring Boot 中使用 @NotEmpty 约束来验证 HTTP 请求正文?

标签 java spring-boot rest validation spring-mvc

我有一个 RestController,其中包含用于创建新用户的 HTTP 端点。

@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 模型如下:

@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 约束?

最佳答案

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;

关于java - 如何在 Spring Boot 中使用 @NotEmpty 约束来验证 HTTP 请求正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65705670/

相关文章:

spring-boot - DateTimeFormatter.ISO_OFFSET_DATE_TIME 未按预期工作

wcf - 读取命名空间时发生 ReadAsDataContract 异常

c# - 从 C#/XAML Metro 应用程序使用 REST 服务?

java - 使用 StuartMacKay 的 transform-swf 库从 swf 读取文本

java - 使用java流实现map-reduce

spring - 如何从环境变量添加事件的 Spring 配置文件?

java - 同步访问 REST Web 服务

java - 从千兆字节文件中读取

java - WebSocket 在打开连接时收到 404

java - 在 Spring v1.5.14.RELEASE 中模拟返回 List 的 RestTemplate