[英]@Valid (jsr 303) not working in Spring mvc 3.0
I'm trying to achieve the JSR 303 bean validation in Spring 3.0 by using a simple login use case. 我试图通过使用一个简单的登录用例在Spring 3.0中实现JSR 303 bean验证。 The problem is if I submit the form without any value the validation is not happening (ie the BindingResult method hasErrors() always returning 'false' and printing I'm cool ! . Following is the code snippet: 问题是如果我提交没有任何值的表单,验证没有发生(即BindingResult方法hasErrors()总是返回'false'并且打印我很酷! 。以下是代码片段:
@Controller
public class AnnotatedController {
@RequestMapping(value = "login")
public String validateLogin(@Valid LoginForm loginForm, BindingResult result, HttpServletRequest request) {
if(result.hasErrors())
System.out.println("Got Errors !");
else
System.out.println("I'm cool !");
return "login";
}
}
The bean looks like this : bean看起来像这样:
public class LoginForm {
@NotEmpty
private String userName;
@Size(min=2, max=3)
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Finally the view: 最后看法:
<table>
<form:form action="login.htm" modelAttribute="loginForm">
<tr>
<td>User :</td>
<td><form:input path="userName" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:input path="password" /></td>
</tr>
<tr><td><input type="submit" value="Ok"> </tr>
</form:form>
</table>
What am I missing ? 我错过了什么?
在servlet上下文XML中添加<mvc:annotation-driven/>
为我解决了这个问题。
you are missing form error tag.use like 你缺少表单错误标签。如
<table>
<form:form action="login.htm" commandName="logindetails">
<tr>
<td>User :</td>
<td><form:input path="userName" /></td>
<td><form:errors path="userName" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:input path="password" /></td>
<td><form:errors path="password" /></td>
</tr>
<tr><td><input type="submit" value="Ok"> </tr>
</form:form>
and also you have to maintain property file with error message. 并且您还必须使用错误消息维护属性文件。
NotEmpty.logindetails.userName = userName is required!
Range.logindetails.password= password value must be between 2 and 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.