1

我正在尝试通过使用简单的登录用例在 Spring 3.0 中实现 JSR 303 bean 验证。问题是,如果我提交没有任何值的表单,则不会发生验证(即 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";
    }
}

豆看起来像这样:

    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;
    }
}

最后是观点:

<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>

我错过了什么?

4

2 回答 2

3

添加<mvc:annotation-driven/>servlet 上下文 XML 为我解决了这个问题。

于 2013-02-27T03:27:01.273 回答
0

你缺少表单错误标签。使用喜欢

<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>

而且您还必须维护带有错误消息的属性文件。

NotEmpty.logindetails.userName = userName is required!
Range.logindetails.password= password value must be between 2 and 3

示例:点击这里

于 2014-07-30T04:26:19.870 回答