我无法在JSP页面中显示验证错误消息。验证有效,但消息根本没有显示。
SystemValidator类:
@Override
public void validate(Object target, Errors errors) {
SystemUser systemUser = (SystemUser) target;
SystemUser user = systemUserRepository.findByUsername(systemUser.getUsername());
if (user != null && !(user.getId() == systemUser.getId()) || superUserName.equalsIgnoreCase(systemUser.getUsername())) {
errors.rejectValue("username", "Duplicate Username");
}
}
视图:
<form:form method="post" modelAttribute="user" action="addUser">
<div class="form-group">
<label for="username" class="col-form-label">User Name</label>
<form:input type="text" required="required" class="form-control" id="username" path="username"/>
<form:errors path = "username" cssClass = "error" />
</div>
<form:input type="hidden" id="id" name="id" path="id"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form:form>
控制器类:
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String saveUser(Model model, @Validated @ModelAttribute("user") SystemUser user, BindingResult result) {
logger.info("User save/update request received [{}]", user.toString());
if (result.hasErrors()) {
loadData(model);
model.addAttribute("user", user);
return "users";
}
systemUserService.saveSystemUser(user);
loadData(model);
return "users";
}
private void loadData(Model model) {
model.addAttribute("users", systemUserService.getAllUsers());
model.addAttribute("user", new SystemUser());
}
答案 0 :(得分:0)
使用@Valid
代替@Validated
,如下所示。
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String saveUser(@Valid @ModelAttribute("user") SystemUser user, BindingResult result,Model model)
答案 1 :(得分:0)
发生验证错误时,请勿执行model.addAttribute("user", new SystemUser());
。
更改为此:
if (result.hasErrors()) {
loadData(model, user);
return "users";
}
并且:
private void loadData(Model model, User user) {
model.addAttribute("users", systemUserService.getAllUsers());
model.addAttribute("user", user);
}