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;
}
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With