简体   繁体   中英

How do I use @NotEmpty constraint to validate an HTTP request body in Spring Boot?

I have a RestController containing an HTTP endpoint to create a new user.

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

My UserRequest model is as follows:

@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(NON_NULL)
@NoArgsConstructor
public class UserRequest {

  // @NotNull
  @NotEmpty private String name;
}

Now, every time I invoke the POST /user endpoint with a valid payload (eg, { "name": "John" } ), I get the following error:

HV000030: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.String'. Check configuration for 'name'"

In other words, the exception is thrown regardless of whether the "name" property was empty or not.

However, when I use the @NotNull constraint instead, the exception is only thrown in the absence of the name property or { "name": null } , as expected.

Am I misusing the @NotEmpty constraint?

For validation String's variable, you should use @NotBlank this constraint check null and blank value for String's variable(blank for example "" or " ") or @NotNull if you want to check the only nullable value

@NotEmpty for Collection's type check.

Check this for more information: https://www.baeldung.com/java-bean-validation-not-null-empty-blank

Maven dependencies (in 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>

In the user request model-

import javax.validation.constraints.NotEmpty; 

@NotEmpty(message = "Name cannot be empty")
    private String name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM