【问题标题】:Form input constraints not being enforced?表单输入约束没有被强制执行?
【发布时间】:2011-05-04 19:23:20
【问题描述】:

我是 Tomcat 和 Spring Web 的新手。我正在尝试通过关注this tutorial 来使用 Spring 的表单验证功能。除了一件事之外,一切似乎都运行得很顺利……我的表单没有进行任何验证,无论我提供哪些数据,当我发送表单时,我总是可以进入成功页面。

我是否正确使用了约束?我想强制用户填写他们的名字,并且名字至少有两个字符长。

package net.devmanuals.form;

import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;

public class RegistrationForm {
    @NotEmpty(message = "You surely have a name, don't you?")
    @Size(min = 2, message = "I'm pretty sure that your name consists of more than one letter.")
    private String firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return this.firstName;
    }
}

表格代码:

    <form:form method="post" commandName="regform">
        <p><form:input path="firstName" /> <form:errors path="firstName" /></p>
        <p><input type="submit" /></p>
    </form:form>

控制器:

@Controller
@RequestMapping("/register")
public class RegistrationController {
    @RequestMapping(method = RequestMethod.GET)
    public String showRegForm(Map model) {
        RegistrationForm regForm = new RegistrationForm();
        model.put("regform", regForm);
        return "regform";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String validateForm(@Valid RegistrationForm regForm, BindingResult result, Map model) {
        if (result.hasErrors()) {
            return "regform";
        }

        model.put("regform", regForm);
        return "regsuccess";
    }
}

我是否错误地应用了约束?

【问题讨论】:

  • 你的配置中有&lt;mvc:annotation-driven/&gt;吗?
  • 哎呀。我尝试将其添加到我的Dispatcher-servlet.xml,但部署后出现此错误:元素“mvc:annotation-driven”的前缀“mvc”未绑定。
  • 在你的配置中为 mvc 添加命名空间,即 xmlns:mvc="springframework.org/schema/mvc" .....

标签: spring tomcat spring-mvc


【解决方案1】:

除了将&lt;mvc:annotation-driven/&gt; 添加到您的配置之外,您还需要确保 JSR-303 jar 在您的类路径中。来自docs

[AnnotationDrivenBeanDefinitionParser] ... 如果指定,则配置验证器,否则默认为由默认 LocalValidatorFactoryBean 创建的新 Validator 实例如果 JSR-303 API 存在于类路径中。

【讨论】:

  • slf4j-api-1.6.1.jar 添加到我的库列表后(我已经拥有了Hibernate Validator),一切似乎都运行顺利。
猜你喜欢
  • 1970-01-01
  • 2012-12-05
  • 1970-01-01
  • 2023-02-07
  • 2018-03-07
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多