我通过了What is the use of BindingResult interface in spring MVC?和https://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-adding-validation-to-a-rest-api/链接。
我在这里发现了两种情况:
情况1::在一个控制器中使用@Valid
注释,但不将BindingResult bindingResult
与if (bindingResult.hasErrors())
方法一起使用
@RequestMapping(value = "/api/comment", method = RequestMethod.POST)
@ResponseBody
public CommentDTO add(@Valid @RequestBody CommentDTO comment) {
........
........
......
return comment;
}
带有@ControllerAdvice
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ValidationErrorDTO processValidationError(MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors();
return processFieldErrors(fieldErrors);
}
情况2:
同时使用@Valid
和@BindingResult
和
@PatchMapping
public ResponseEntity<HttpStatus> updateEmployee(@Valid @RequestBody EmployeeDto dto, BindingResult br){
if (br.hasErrors()) {
throw new InvalidRequestException("Invalid resource", br);
}
employeeService.updateEmployee(dto);
return new ResponseEntity<>(HttpStatus.OK);
}
现在,为了显示所有字段都有验证问题的详细信息并设置/获取一些错误消息等,最好从BindingResult
变量中获取。