@Valid(JSR 303)在Spring MVC 3.0中不起作用 [英] @Valid (jsr 303) not working in Spring mvc 3.0

查看:320
本文介绍了@Valid(JSR 303)在Spring MVC 3.0中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用简单的登录用例在Spring 3.0中实现JSR 303 Bean验证.问题是如果我提交的表单没有任何值,验证就不会发生(即BindingResult方法hasErrors()总是返回'false'并打印我很酷!.以下是代码段:

I'm trying to achieve the JSR 303 bean validation in Spring 3.0 by using a simple login use case. The problem is if I submit the form without any value the validation is not happening (i.e the BindingResult method hasErrors() always returning 'false' and printing I'm cool !. Following is the code snippet:

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

bean看起来像这样:

The bean looks like this :

    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>

我想念什么?

推荐答案

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

Adding <mvc:annotation-driven/>in servlet context XML fixed the issue for me.

这篇关于@Valid(JSR 303)在Spring MVC 3.0中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆