![](/img/trans.png)
[英]Having trouble in Spring MVC form validation using hibernate-validator and JSR-303
[英]Hibernate-validator Groups with Spring MVC
我正在使用hibernate-validator 4.3.1和Spring MVC 3.2.3。
我的应用程序有一个具有以下属性和注释的Bean(为了简化起见,我删除了其中的大多数属性):
public class Account {
@NotEmpty(groups = GroupOne.class)
private String name;
@NotEmpty(groups = GroupOne.class)
private Date creationDate;
@NotEmpty(groups = GroupTwo.class)
private String role;
@NotEmpty(groups = GroupTwo.class)
private String profile;
//getters and setters
}
如图所示,由于应用程序具有由两个步骤组成的向导形式,因此分为两组验证:第一步,名称和creationDate字段由用户填充,第二步,角色和配置文件字段。
我添加一些Controller方法作为示例:
@RequestMapping(value = "/account/stepOne", method = "POST")
public String stepOne(@ModelAttribute @Validated(GroupOne.class) Account account, BindingResult bindingResult) {
//Implementation
}
@RequestMapping(value = "/account/stepTwo", method = "POST")
public String stepTwo(@ModelAttribute @Validated(GroupTwo.class) Account account, BindingResult bindingResult) {
//Implementation
}
以上方法指定必须通过@Validated注释应用哪些验证。
到目前为止,一切正常,但是当我想以另一种形式重用该bean时,我遇到了一些问题。 此表单显示Bean的所有字段,并且接收提交的控制器方法如下:
@RequestMapping(value = "/account/stepOne", method = "POST")
public String stepOne(@ModelAttribute @Validated Account account, BindingResult bindingResult) {
//Implementation
}
如您所见,该组的名称已从@Validated批注中删除,因为我要应用Account Bean中定义的所有验证。
但是,它不起作用,并且使其起作用的唯一方法是将Default组添加到bean的属性中,如下所示:
public class Account {
@NotEmpty(groups = {GroupOne.class, Default.class})
private String name;
@NotEmpty(groups = {GroupOne.class, Default.class})
private Date creationDate;
@NotEmpty(groups = {GroupTwo.class, Default.class})
private String role;
@NotEmpty(groups = {GroupTwo.class, Default.class})
private String profile;
//getters and setters
}
有没有更优雅的方法来实现这一目标?
没有别的优雅方法。 在不指定组的情况下进行验证将验证默认组。 因此,您必须按说明添加它。 唯一的替代方法是通过@Validated({GroupOne.class, GroupTwo.class})
显式验证您感兴趣的所有组。 我想这是您喜欢的口味问题。
您可以使用@Valid :
public ModelAndView myMethod(@ModelAttribute @Valid MyDto myDto, BindingResult result){
if(result.hasErrors()){
....
}
如果您使用默认扩展您的组接口,它应该照顾好自己。
喜欢
public interface Group1 extends Default {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.