Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define parameters in Spring RequestBody as not null?

I want to be able to define certain variables as not null in Spring's @RequestBody. That way Spring's controller will reject any requests whose body doesn't have certain variables that I define as critical. I've tried the code below however it doesn't work:

The controller:

@PutMapping("/")
ResponseEntity updateOptions(
   @RequestBody RequestDto requestDto
);

The RequestDto, I want the first parameter to always be filled:

import javax.validation.constraints.NotNull;

public class RequestDto {
   @NotNull
   String id;

   String message;
}
like image 210
Iron Toad Tough Avatar asked Oct 12 '25 00:10

Iron Toad Tough


1 Answers

You need to add the @Valid annotation.

@PutMapping("/")
ResponseEntity updateOptions(
   @Valid @RequestBody RequestDto requestDto
);

If you are using Spring Boot 2.3 and higher, we also need to add the "spring-boot-starter-validation" dependency:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-validation</artifactId> 
</dependency>

For more detailed examples you can review the article "Validation in Spring Boot".

like image 174
İsmail Y. Avatar answered Oct 14 '25 13:10

İsmail Y.