带有注释的 Spring 引导验证



我正在尝试使用@Valid验证请求正文。这是我读到的一篇关于此的文章:https://dimitr.im/validating-the-input-of-your-rest-api-with-spring。 这是我的代码:

@PutMapping("/update")
public ResponseEntity<?> update(@RequestBody @Valid ProfileDTO medicationDTO) {
try {
profileService.update(medicationDTO);
} catch (Exception e) {
return ResponseEntity
.badRequest()
.body(new MessageResponseDTO("Error: User not found!"));
}
return ResponseEntity.ok(new MessageResponseDTO("User updated successfully!"));
}
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ProfileDTO {
private Integer userId;
private String username;
private String email;
@NotBlank(message = "First name cannot be empty.")
@Min(1)
private String firstName;
@NotBlank(message = "Last name cannot be empty.")
@Min(1)
private String lastName;
@NotBlank(message = "Registration plate cannot be empty.")
@Min(1)
private String registrationPlate;
}

但是,当我尝试从邮递员状态发送此消息时,返回了 200:

{
"userId": "2",
"firstName": "",
"lastName": "Smith",
"registrationPlate": "AB20CDE"
}

为什么验证不起作用?

您在服药后立即错过了BindingResultDTO,例如:

public ResponseEntity<?> update(@RequestBody @Valid ProfileDTO medicationDTO, BindingResult bindingResult) 

您需要检查bindingResult.hasErrors()是否为真,然后抛出所需的异常。

最新更新