2011-05-04 69 views
0

我是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"; 
    } 
} 

我是否施加的约束不正确?

+0

你的配置中是否有''? – skaffman 2011-05-04 19:36:52

+0

哎呀。我尝试将它添加到我的'Dispatcher-servlet.xml'中,但部署后出现此错误:*未绑定元素“mvc:annotation-driven”的前缀“mvc”。* – Pieter 2011-05-04 19:56:11

+0

在您的配置中为mvc添加命名空间,即xmlns:mvc =“http://www.springframework.org/schema/mvc”..... – 2011-05-04 23:50:21

回答

0

除了将<mvc:annotation-driven/>添加到您的配置之外,还需要确保JSR-303 jar包在您的类路径中。从docs

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

+0

将'slf4j-api-1.6.1.jar'添加到我的库列表(我已经有了Hibernate Validator),一切似乎都在顺利进行。 – Pieter 2011-05-08 07:54:21