Spring MVC 3 Validation not working
I have a bean to validate using jsr-303 but the BIndingResult returns no error. every time it returns to the success view
My Bean is
public class User
{
//@NotNull
private int userId;
@NotNull
@Size(min=3,max=100)
private String userName;
@NotNull
@Size(max=60)
private String userFullName;
}
my controller is
@RequestMapping(value="/user")
@Controller
public class UserController{
@RequestMapping(value="/create",method=RequestMethod.GET)
public String createUserForm开发者_如何学编程(Map model)
{
model.put("user",new User());
return "createUserForm";
}
@RequestMapping(value="/create",method=RequestMethod.POST)
public String createUser (@Valid @ModelAttribute("user") User user,BindingResult result,Map model)
{
if(result.hasErrors())
{
return "createRmsUserForm";
}
else
{
model.put("User",user);
return "redirect:/home";
}
}
}
- you need a javax.validation provider on your classpath (for example hibernate-validator-4.x.jar)
- you need to enable it in
dispatcher-servlet.xml
.<mvc:annotation-driven />
is the easiest way.
if you are using maven
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
Why you show another page when error occurs? Try to return user to the same page: in your case createUserForm
instead of createRmsUserForm
.
精彩评论