【发布时间】:2015-09-29 12:39:50
【问题描述】:
我的 UserValidator 类有问题。我正在尝试验证 2 个表单字段:用户名和电子邮件,并且只有在用户名的情况下才会显示messahe。这对我来说很奇怪,因为我在这两种情况下都是以同样的方式做的。
我有 globalmessages.properties 文件,其中包含我的错误消息:
same.mail=Email exists, type other email!
equal.user=Username exists, type other username!
UserValidator 类以这种方式在 Controller 中进行验证:
@Autowired
private UserValidator userValidator;
@RequestMapping(value = "/adduser", method = RequestMethod.GET)
public String addUser(@Valid @ModelAttribute(value = "user") User user, BindingResult result) {
userValidator.validate(user, result);
return "signin";
}
在验证方法中,我正在检查用户是否存在于数据库中,如果存在则注册错误。然后我对电子邮件做同样的事情。这就是 UserValidator 的 validate 方法:
@Override
public void validate(Object target, Errors errors) {
User user = (User) target;
//check if user exists
Users users = usersDAOImpl.checkByUsername(user.getUsername());
//check if email exists
Emails email = usersDAOImpl.checkByEmail(user.getEmail());
String emailAddresse = email == null ? "null" : "not null";
System.out.println("From UserValidator class, before rejecting values- email: "
+ emailAddresse);
if (users != null)
{
errors.rejectValue("username", "equal.user");
System.out.println("From UserValidator class - user not null: "
+ users.getUsername());
}
if (email != null)
{
errors.reject("email", "same.mail");
System.out.println("From UserValidator class - email not null: "
+ email.getEmail());
}
}
这是我的登录表单:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<form:form modelAttribute="user" method="get" action="${pageContext.request.contextPath}/adduser" >
<table align="left">
<tr>
<td>Username</td>
<td><form:input path="username" /></td>
<td><font color="red"><form:errors path="username"></form:errors></font></td>
</tr>
<tr>
<td>Password</td>
<td><form:input type="password" path="password" /></td>
<td><font color="red"><form:errors path="password"></form:errors></font></td>
</tr>
<tr>
<td>Confirm password</td>
<td><form:input type="password" path="confpassword" /></td>
<td><font color="red"><form:errors path="confpassword"></form:errors></font></td>
</tr>
<tr>
<td>E-mail</td>
<td><form:input type="email" path="email" /></td>
<td><font color="red"><form:errors path="email"></form:errors></font></td>
</tr>
<tr>
<td><input type="submit" value="Create user"></td>
</tr>
</table>
</form:form>
</body>
</html>
当我输入现有用户名并提交表单时,显示来自 globalmessages.properties 的用户名错误,当我输入现有电子邮件时,不显示错误消息,尽管 usersDAOImpl.checkByEmail 方法工作正常,我可以看到“来自UserValidator 类 - 电子邮件不为空:" + email.getEmail() 在控制台上。
【问题讨论】:
-
在控制器中,检查if(bindingResult.hasErrors()),如果是,那么你有错误。另外,显示您的模型类,因为验证是基于此的。
标签: java spring validation