Issue
I have method which have BindingResult.
@PostMapping("/spare-create")
public String saveSpare(@Valid Spares spares, BindingResult bindingResult, RedirectAttributes attributes) {
if (bindingResult.hasErrors()) {
attributes.addAttribute("orderNumberError", spares.getOrderNumber());
attributes.addAttribute("orderMarkError", spares.getOrderMark());
List<ObjectError> errors = bindingResult.getAllErrors();
errors.forEach(element -> System.out.print(errors + ""));
return "redirect:/ab2";
} else {
sparesServiceImpl.saveSpares(spares);
return "redirect:/new-docs";
}
}
I tried to get all errors, but get output like
[Field error in object 'spares' on field 'orderNumber': rejected value [12345]; codes [Size.spares.orderNumber,Size.orderNumber,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [spares.orderNumber,orderNumber]; arguments []; default message [orderNumber],2147483647,6]; default message [размер должен находиться в диапазоне от 6 до 2147483647]]
How can I get data in format like: "Field and value"?
Solution
As long as you're interested only in field errors you can call getFieldErrors()
method on BindingResult
instead of getAllErrors()
, which will return collection of FieldError
s instead of ObjectError
s.
FieldError
provides access to field name and rejected value, so you can achieve your goal like that:
bindingResult.getFieldErrors()
.forEach(e -> System.out.println(
"field: " + e.getField() + ", rejected value: " + e.getRejectedValue()));
Answered By - AndrewThomas
Answer Checked By - Candace Johnson (JavaFixing Volunteer)