我正在尝试使用@Valid验证RequestBody。这是我阅读的有关此文章: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"
}
为什么验证无效?
您在药DTO之后立即缺少BindingResult
,例如:
public ResponseEntity<?> update(@RequestBody @Valid ProfileDTO medicationDTO, BindingResult bindingResult)
并且您需要检查bindingResult.hasErrors()
是否为真,然后引发所需的异常。