我从验证器发送消息到查看时遇到问题。当我调试验证器时,返回错误消息,但我不知道如何在视图中显示。我尝试了其他方式来验证表单,但始终不显示来自验证器的消息。
SignConfiguration类
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public ModelAndView createUser(@ModelAttribute("user") @Validated User user, BindingResult bindingResult) {
ModelAndView model = new ModelAndView();
model.addObject("user", user);
if (bindingResult.hasErrors()) {
signupValidation.validate(user,bindingResult);
model.setViewName("view/signup");
} else {
userService.saveUser(user);
model.addObject("msg", "Correct registration!");
model.addObject("user", new User());
model.setViewName("view/signup");
}
return model;
}
SignupValidator类
public class SignupValidation implements Validator {
@Override
public boolean supports(Class<?> aClass) {
return User.class.equals(aClass);
}
@Override
public void validate(Object o, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"firstname", "signup.error.blank.field");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"lastname", "signup.error.blank.field");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"email", "signup.error.blank.field");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"password", "signup.error.blank.field");
}
signup.html
<div class="popup-window">
<div class="popup-content">
<form class="form-input" role="form" method="POST" th:action="@{/signup}" th:object="${user}">
<a th:href="@{/}" class="close" id="close-sign-up">+</a>
<div class="user-input">
<label for="email" th:text="|#{signup.email.placeholder}:|"></label>
<input type="text" th:field="*{email}" id="email" name="email"
th:placeholder="#{signup.email.placeholder}">
<div class="error-email" role="alert" th:if="${#fields.hasErrors('email')}" th:error="*{email}"
></div>
</div>
<div class="user-input">
<div class="correct-register" role="alert" th:if="${msg}" th:text="${msg}"></div>
<button type="submit" th:text="#{welcome.signup}"></button>
</div>
</form>
</div>