@Valid(JSR 303)中的Spring MVC 3.0不工作(@Valid (jsr 303

2019-07-30 04:59发布

我想通过一个简单的登录用例实现在Spring 3.0的JSR 303 Bean验证。 问题是,如果我提交表单未经验证是不会发生任何值(即BindingResult方法hasErrors()总返回“假”,并打印我很酷,以下是代码片段:

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

我在想什么?

Answer 1:

添加<mvc:annotation-driven/>在servlet上下文XML固定我的问题。



Answer 2:

你缺少的形状误差tag.use喜欢

<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

例如:点击这里



文章来源: @Valid (jsr 303) not working in Spring mvc 3.0