demo.java
@RequestMapping(value = "/user/create", method = RequestMethod.POST)
public String create(@Validated @ModelAttribute UserRequest userRequest, BindingResult result, Model model) {
if (result.hasErrors()) {
List<String> accountNameErrors = new ArrayList<>();
List<String> loginIdErrors = new ArrayList<>();
List<String> passwordErrors = new ArrayList<>();
for (ObjectError error : result.getAllErrors()) {
String defaultMessage = Objects.requireNonNull(error.getDefaultMessage());
String errorMessage = messageSource.getMessage(defaultMessage, null, defaultMessage, LocaleContextHolder.getLocale());
if (defaultMessage.contains("アカウント名")) {
accountNameErrors.add(errorMessage);
} else if (defaultMessage.contains("ログインID")) {
loginIdErrors.add(errorMessage);
} else if (defaultMessage.contains("パスワード")) {
passwordErrors.add(errorMessage);
}
}
model.addAttribute("accountNameErrors", accountNameErrors);
model.addAttribute("loginIdErrors", loginIdErrors);
model.addAttribute("passwordErrors", passwordErrors);
return "user/add";
}
userService.create(userRequest);
return "redirect:/user/list";
}
title.html
<div th:if="${accountNameErrors}">
<div th:each="error : ${accountNameErrors}">
<p th:text="${error}"></p>
</div>
</div>
<div th:if="${loginIdErrors}">
<div th:each="error : ${loginIdErrors}">
<p th:text="${error}"></p>
</div>
</div>
<div th:if="${passwordErrors}">
<div th:each="error : ${passwordErrors}">
<p th:text="${error}"></p>
</div>
</div>