Spring Rest Add @NotEmpty in @RequestBody without creating request POJO

Viewed 2859

I want to add @NotEmpty in @RequestBody, but i don't want to create additional POJO just for the request, how can i do that?

I want to do like the following, but it still return me 201 Created status code when i put [] in request body, it means that @NotEmpty is actually not working.

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@Valid @NotEmpty @RequestBody Set<String> request) {
      .....
}

I DO NOT WANT to do something like this, but the @NotEmpty works in this case :

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@Valid @NotEmpty @RequestBody SampleRequest request) {
      .....
}

SampleRequest class

public class SampleRequest {

    @NotEmpty
    private Set<String> name;

     ..Setter and Getter
}
3 Answers

As you're not validating complex Java objects like DTOs, so you can put constraint (validation annotations) on your method parameters.

You only need to do two things

1-put constraint (valiadtion) annotation before the method parameter

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody @NotEmpty SampleRequest request) {
      .....
}

2-Put @Validated on the class

@Validated
public class testController{

 //..

}

Finally, we have

@Validated
public class testController{

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody @NotEmpty SampleRequest request) {
      //..
   }

}

Some helpful link

Spring REST Validation Example

All You Need To Know About Bean Validation With Spring Boot

Related