问题
I'm using hibernate-validator 4.3.1 and Spring MVC 3.2.3.
My application has a bean with the following properties and annotations (I've removed most of them to make it simple):
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
}
As it is showed, there are two groups of validations because the application has a wizard-form composed of two steps: in the first step the name and creationDate fields are filled by the user and in the second step the role and profile fields.
I add some Controller methods as example:
@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
}
The above methods specify which validation has to be applied by @Validated annotation.
Until now everything works fine, but I have some problems when I want to reuse that bean in another form. This form displays all the fields of the bean and the controller's method which receives the submit is the following:
@RequestMapping(value = "/account/stepOne", method = "POST")
public String stepOne(@ModelAttribute @Validated Account account, BindingResult bindingResult) {
//Implementation
}
As you can see, the name of the group has been removed from the @Validated annotation because I want to apply all the validations defined in Account bean.
However, it didn't work and the only way to make it work has been to add the Default group to the bean's properties, as so:
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
}
Is there a more elegant way to achieve this?
回答1:
There is no more elegant way. Validating without specifying a group will validate the default groups. Hence you have to add it as described. The only other alternative is to explicitly validate all groups you are interested in via @Validated({GroupOne.class, GroupTwo.class})
. I guess it is a matter of taste what you prefer.
回答2:
You can use @Valid:
public ModelAndView myMethod(@ModelAttribute @Valid MyDto myDto, BindingResult result){
if(result.hasErrors()){
....
}
回答3:
if you extend your Group Interface with Default, it should take care of itself.
Like
public interface Group1 extends Default {}
来源:https://stackoverflow.com/questions/24680607/hibernate-validator-groups-with-spring-mvc