2011-06-13 108 views
2

我有一个使用jsr-303进行验证的bean,但BIndingResult不返回错误。每次返回到成功视图时间Spring MVC 3验证不起作用

我Bean是

public class User 
{ 

    //@NotNull 
    private int userId; 


    @NotNull 
    @Size(min=3,max=100) 
    private String userName; 

    @NotNull 
    @Size(max=60) 
    private String userFullName; 
} 

我控制器

@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"; 

     } 
    } 
} 

回答

6
  • 你需要在你的classpath中javax.validation提供商(例如休眠,验证-4.x.jar)
  • 您需要在dispatcher-servlet.xml中启用它。 <mvc:annotation-driven />是最简单的方法。
+0

我已经尝试添加hibernate-validator-4.0.0.Beta1.jar,并且在servlet-context.xml中也添加了。但没有任何变化:( – 2011-06-13 11:28:56

+0

显示我的调度程序servlet xml。此外,hibernate验证程序不是很长时间的beta版本 - 抓取更新的版本。 – Bozho 2011-06-13 11:30:14

+0

2011-06-13 11:36:28

2

如果你使用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> 
1

为什么你展示另一个网页时出现的错误?尝试将用户返回到同一页面:在您的案例中,createUserForm而不是createRmsUserForm