可以通过groups
属性将Bean验证中的验证约束添加到一个或多个组。 这使您可以限制在验证期间应用的约束集。 在某些小组应先于其他小组进行验证(例如在向导中)的情况下,这可能很方便。 从Spring MVC 3.1开始,可以通过org.springframework.validation.annotation.Validated
注释使用验证组进行自动验证。 在本文中,我将使用简单的Spring MVC应用程序来演示如何轻松使用验证组来验证Spring的MVC模型属性。
形成
让我们从将逐步验证的表单类开始。 首先,我们定义代表约束组的接口:
public class Account implements PasswordAware {interface ValidationStepOne {// validation group marker interface}interface ValidationStepTwo {// validation group marker interface}
}
验证约束
接下来,我们将约束分配给组。 请记住,如果您不提供组,则将使用默认组。 另请注意@SamePasswords
和@StrongPassword
–自定义约束,必须定义groups
属性:
@SamePasswords(groups = {Account.ValidationStepTwo.class})
public class Account implements PasswordAware {@NotBlank(groups = {ValidationStepOne.class})private String username;@Email(groups = {ValidationStepOne.class})@NotBlank(groups = {ValidationStepOne.class})private String email;@NotBlank(groups = {ValidationStepTwo.class})@StrongPassword(groups = {ValidationStepTwo.class})private String password;@NotBlank(groups = {ValidationStepTwo.class})private String confirmedPassword;// getters and setters
}
巫师
有了Account
,我们可以创建一个三步向导@Controller
,该向导将允许用户创建一个帐户。 第一步,我们将让Spring验证ValidationStepOne
组中的约束:
@Controller
@RequestMapping("validationgroups")
@SessionAttributes("account")
public class AccountController {@RequestMapping(value = "stepOne")public String stepOne(Model model) {model.addAttribute("account", new Account());return VIEW_STEP_ONE;}@RequestMapping(value = "stepOne", method = RequestMethod.POST)public String stepOne(@Validated(Account.ValidationStepOne.class) Account account, Errors errors) {if (errors.hasErrors()) {return VIEW_STEP_ONE;}return "redirect:stepTwo";}
}
为了触发组的验证,我使用了@Validated
注解。 该批注采用带有组类型的var-arg参数。 代码@Validated(ValidationStepOne.class)
触发ValidationStepOne
组中约束的ValidationStepOne
。
在下一步中,我们将让Spring在ValidationStepTwo
组中验证约束:
@Controller
@RequestMapping("validationgroups")
@SessionAttributes("account")
public class AccountController {@RequestMapping(value = "stepTwo")public String stepTwo() {return VIEW_STEP_TWO;}@RequestMapping(value = "stepTwo", method = RequestMethod.POST)public String stepTwo(@Validated(Account.ValidationStepTwo.class) Account account, Errors errors) {if (errors.hasErrors()) {return VIEW_STEP_TWO;}return "redirect:summary";}
}
在摘要步骤中,我们将确认输入的数据,并让Spring验证两组的约束:
@Controller
@RequestMapping("validationgroups")
@SessionAttributes("account")
public class AccountController {@RequestMapping(value = "summary")public String summary() {return VIEW_SUMMARY;}@RequestMapping(value = "confirm")public String confirm(@Validated({Account.ValidationStepOne.class, Account.ValidationStepTwo.class}) Account account, Errors errors, SessionStatus status) {status.setComplete();if (errors.hasErrors()) {// did not pass full validation}return "redirect:start";}
}
在Spring 3.1之前,您可以手动触发验证。 我在以前的一篇文章中对此进行了描述: http : //blog.codeleak.pl/2011/03/how-to-jsr303-validation-groups-in.html
注意:如果要在不使用Spring的情况下使用验证组,则需要将组传递给javax.validation.Validator#validate()
:
没有Spring的验证组
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Account account = new Account();// validate with first group
Set<ConstraintViolation<Account>> constraintViolations =validator.validate(account, Account.ValidationStepOne.class);
assertThat(constraintViolations).hasSize(2);// validate with both groups
Set<ConstraintViolation<Account>> constraintViolations =validator.validate(account, Account.ValidationStepOne.class, Account.ValidationStepTwo.class);
assertThat(constraintViolations).hasSize(4);
这也是测试验证的最简单方法:
public class AccountValidationTest {private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();@Testpublic void shouldHaveFourConstraintViolationsWhileValidatingBothGroups() {Account account = new Account();Set<ConstraintViolation<Account>> constraintViolations = validator.validate(account, Account.ValidationStepOne.class, Account.ValidationStepTwo.class);assertThat(constraintViolations).hasSize(4);}@Testpublic void shouldHaveTwoConstraintViolationsWhileStepOne() {Account account = new Account();Set<ConstraintViolation<Account>> constraintViolations = validator.validate(account, Account.ValidationStepOne.class);assertThat(constraintViolations).hasSize(2);}
}
使用Spring Test进行测试验证
如果验证/绑定失败,使用Spring Test进行测试验证将提供更复杂的测试方法。 对于示例,请查看我的另一篇博客文章: Spring MVC集成测试:断言给定的模型属性具有全局错误
- 可以在这里找到本文的源代码: https : //github.com/kolorobot/spring-mvc-beanvalidation11-demo
翻译自: https://www.javacodegeeks.com/2014/08/validation-groups-in-spring-mvc.html