在 Rest API 中注释的 RequestBody Dto 的 Spring Boot 验证



在我的控制器中,我用@Valid注释注释了请求参数,用@NotNull注释注释了 DTO 的字段,但验证似乎不起作用。

是否有任何配置要进行才能继续进行验证?下面是控制器和 DTO 类的详细信息。

@RepositoryRestController
@RequestMapping(value = "/download_pdf")
public class PurchaseController {
    @Autowired
    private IPurchaseService iPurchaseService;
    @Loggable
    @RequestMapping(value = "view_order", method = RequestMethod.POST)
    public ResponseEntity getPDF(@RequestBody @Valid CustomerOfferDto offer,
                                 HttpServletResponse response) {
        return iPurchaseService.purchase(offer, response);
    }
}
public class CustomerOfferDto {
    @NotNull
    private String agentCode;
    // getter and setter...
 }

以下是我为使其工作而执行的步骤。

添加依赖项:

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

DTO类中的约束:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ValidTaskDTO
public class TaskDTO {
    @FutureOrPresent
    @NotNull(message = "DueDate must not be null")
    private ZonedDateTime dueDate;
    @NotBlank(message = "Title cannot be null or blank")
    private String title;
    private String description;
    @NotNull
    private RecurrenceType recurrenceType;
    @Future
    @NotNull(message = "RepeatUntil date must not be null")
    private ZonedDateTime repeatUntil;
}

RestController 方法,在请求正文参数上带有@Valid注释

@RestController
@RequestMapping("/tasks")
@Validated
public class TaskController {
    @PostMapping
    public TaskDTO createTask(@Valid @RequestBody TaskDTO taskDTO) {
      .....
    }
}

在使用包含dueDate值的请求正文发出POST请求时null我收到了预期的错误消息,如下所示。

{
  "timestamp": "2021-01-20T11:38:53.043232",
  "status": 400,
  "error": "Bad Request",
  "message": "DueDate must not be null"
}

我希望这有所帮助。有关类级别约束的详细信息,请观看此视频。

在我的项目中,当我将代码从 Entity 更改为 DTO 并且忘记向我的 DTO 参数添加@ModelAttribute时,通常会发生这种情况。

如果您也遇到过这种情况,请尝试将@ModelAttribute("offer")添加到DTO参数中。

最新更新