【问题标题】:Spring form validation using annotation and @Valid使用注解和@Valid 的 Spring 表单验证
【发布时间】:2015-06-10 17:39:27
【问题描述】:

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

控制器:

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

当我输入空值(用户名、密码和重复密码)时,不会发生错误(我已经使用调试器检查过)。所以看起来没有执行验证。从视图绑定值没问题(使用调试器检查)有什么想法可能是错误的吗?

【问题讨论】:

  • 也添加@NotEmpty注解。
  • @StanislavL 我做到了,但什么也没做。无论如何 - 当我输入一些随机字符(最多 4 个)时,什么也没有发生。
  • 从表单中移除 action 属性

标签: java spring spring-mvc


【解决方案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

【讨论】:

  • 谢谢, 帮助了 :)
猜你喜欢
  • 2015-01-04
  • 2012-12-31
  • 2022-01-01
  • 2018-07-14
  • 2021-12-09
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多