spring-mvc form validation
I have program with form vaidation in 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);
}
}
Person bean:
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...
}
the form:
<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>
The validation don't work. When i enter value out of the bound 0 to 100 the program continues.
I don't have in my spring config file. when i add it i got:
Error creating bean wi开发者_运维技巧th name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0': Invocation of init method failed; nested exception is javax.validation.ValidationException: Could not create Configuration.
Did you defined validator bean?
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
You may need to add validation
dependency as well..
<dependency>
<groupId>javax.validation</groupId>
<artifactId>com.springsource.javax.validation</artifactId>
<version>1.0.0.GA</version>
</dependency>
精彩评论