java—如何将SpringRequestBody中的参数定义为NOTNULL?

3pvhb19x  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(329)

我希望能够在spring中将某些变量定义为notnull @RequestBody . 这样,spring的控制器将拒绝任何主体没有我定义为关键变量的请求。我尝试了下面的代码,但它不起作用:
控制器:

  1. @PutMapping("/")
  2. ResponseEntity updateOptions(
  3. @RequestBody RequestDto requestDto
  4. );

这个 RequestDto ,我希望始终填充第一个参数:

  1. import javax.validation.constraints.NotNull;
  2. public class RequestDto {
  3. @NotNull
  4. String id;
  5. String message;
  6. }
xqkwcwgp

xqkwcwgp1#

你需要添加 @Valid 注解。

  1. @PutMapping("/")
  2. ResponseEntity updateOptions(
  3. @Valid @RequestBody RequestDto requestDto
  4. );

如果您正在使用 Spring Boot 2.3 更高的是,我们还需要添加“spring boot starter validation”依赖项:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-validation</artifactId>
  4. </dependency>

有关更详细的示例,您可以查看文章“SpringBoot中的验证”。

相关问题