使用注释和@Valid进行Spring表单验证

时间:2015-06-10 17:39:27

标签: java spring spring-mvc

我的表单验证存在一些问题。

控制器:

@RequestMapping(value = REGISTER_URL, method = RequestMethod.POST)
    public String registerPost(@Valid RegisterForm registerForm,
                               BindingResult result) {
        if (result.hasErrors()) {
            return REGISTER_VIEW;
        }
        System.out.println(registerForm.getPassword());
        return LOGIN_VIEW;
    }

查看:

<form:form action="register" commandName="registerForm" method="post">
            <table>
                <tr>
                    <td>Username:</td>
                    <td><form:input path='username' /></td>
                    <td><form:errors path="username"/></td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td><form:password path='password'/></td>
                    <td><form:errors path="password"/></td>
                </tr>
                <tr>
                    <td>Repeat password:</td>
                    <td><form:password path='repeatedPassword'/></td>
                    <td><form:errors path="repeatedPassword"/></td>
                </tr>
                <tr>
                    <td colspan="2">&nbsp;</td>
                </tr>
                <tr>
                    <td colspan='2'><input name="submit" type="submit">&nbsp;<input name="reset" type="reset"></td>
                </tr>
            </table>
        </form:form>

形式:

public class RegisterForm {

    @Size(min = 3, max = 15)
    private String username;

    @Size(min = 5)
    private String password;

    @Size(min = 5)
    private String repeatedPassword;

   // getters and setters omitted
}

当我输入空值(用户名,密码和repeatedPassword)时,没有错误发生(我已使用调试器检查过它)。因此看起来没有执行验证。视图中的绑定值是可以的(使用调试器检查)任何想法可能出错?

1 个答案:

答案 0 :(得分:1)

将以下内容添加到您的上下文中:

<mvc:annotation-driven />
<context:component-scan base-package="xxx.xxx.xxx" />

在指南中,他们使用"@SpringBootApplication" http://spring.io/guides/gs/validating-form-input/

@SpringBootApplication注释相当于使用@Configuration@EnableAutoConfiguration@ComponentScan及其默认属性: http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html