4

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

1 Answer 1

7

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.