I'm having some issues finding out how to validate in spring 3. What i have so far is this Java Bean....
public class User {
@NotEmpty
@Size(min=2, max=40)
private String name="";
@Email
private String email="";
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public void setName(String name){
this.name=name;
}
public void setEmail(String email){
this.email=email;
}
}
This is the method that links to the page containing the form:
@RequestMapping(value="/form", method=RequestMethod.GET)
public String form(Model model){
model.addAttribute("user",new User());
return "form";
}
And this is the method in my controller, which "should" validate
@RequestMapping(value="/displayUser",method=RequestMethod.POST)
public String displayUser(Model model,@Valid User user,BindingResult result){
if(result.hasErrors()){
return "form";
}
userList.add(user);
model.addAttribute("user",use开发者_开发技巧r);
return "displayUser";
}
The @Validate annotation should make the validation, but in my case it does not.
Do you see something wrong in my code?
by the way this is the form i have "all is very simple, this is just for test purposes
<f:form method="post" action="displayUser" commandName="user">
<table align="center" border="1">
<tr>
<td>Your details</td>
</tr>
<tr>
<td><f:label path="name">Name:</f:label></td><td><f:input path="name" /></td><f:errors path="name"></f:errors>
</tr>
<tr>
<td><f:label path="email">Email:</f:label></td><td><f:input path="email" /></td><f:errors path="name"></f:errors>
</tr>
<tr>
<td><input type="submit" value="register" /></td>
</tr>
</table>
</f:form>
Any advise? (i use java 5 and there the javax.validation.Validator isn't available)
Make sure to add javax.validation's validation-api and hibernate validator. If you use maven add the following on your dependencies:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.0.2.GA</version>
</dependency>
Enable Spring annotation driven on your applicationContext
<mvc:annotation-driven />
精彩评论