2011-08-23 144 views
1

我有spring-mvc中的form vaidation程序。spring-mvc表單驗證

import javax.validation.Valid; 

import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.servlet.ModelAndView; 

import com.evgeny.spring.form.beans.Person; 

@Controller 
public class FormController { 

    @RequestMapping(method = RequestMethod.GET,value="some") 
    public ModelAndView goRegistrate(){ 
     ModelAndView mav = new ModelAndView(); 
     mav.addObject("person", new Person()); 
     mav.setViewName("regForm"); 
     return mav; 
    } 

    @RequestMapping(method = RequestMethod.POST,value="reg") 
    public ModelAndView handleForm(@Valid Person person){ 
     person.setId(person.getId()+1); 
     person.setName(person.getName()+"test"); 
     return new ModelAndView("view","personPlus",person); 
    } 
} 

人豆:

public class Person { 
    @Size(max=100, min=0,message="0 to 100") 
    private int id; 
    private String name; 

    public Person(int id, String name) { 
     super(); 
     this.id = id; 
     this.name = name; 
    } 

    public Person() { 
     this.id = 1; 
     this.name = "No name"; 

    } 

    //Getters and Setters... 
} 

形式:

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>Insert title here</title> 
</head> 
<body> 
    <sf:form method="post" modelAttribute="person" action="reg.htm"> 
     <sf:input path="id" id="personId"/> 
     <sf:input path="name"/> 
     <input type="submit" value="Submit"/> 
    </sf:form> 
</body> 
</html> 

驗證不起作用。當我輸入值從0到100的範圍時,程序繼續。

我沒有在我的spring配置文件中。當我添加它我得到:

Error creating bean with name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0': Invocation of init method failed; nested exception is javax.validation.ValidationException: Could not create Configuration. 

回答

0

您是否定義了驗證器bean?

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" /> 

您可能需要添加validation依賴以及..

<dependency> 
    <groupId>javax.validation</groupId> 
    <artifactId>com.springsource.javax.validation</artifactId> 
    <version>1.0.0.GA</version> 
    </dependency>