Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

java - 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;
}
question from:https://stackoverflow.com/questions/65870123/how-to-define-parameters-in-spring-requestbody-as-not-null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...