Group sequence @GroupSequenceProvider, @GroupSequence controls the data verification sequence and solves the problem of multi-field joint logic verification
Hibernate Validator provides Non-standard
@GroupSequenceProvider annotation
. Based on the status of the current object instance, dynamically determine which verification groups to load into the default verification group.
We need to use theDefaultGroupSequenceProvider interface
provided by Hibernate Validation to handle the circumstances under which those properties enter the specified group.
⏹Note that the custom check value cannot be empty
@Documented @Target({ ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = {ValidateIntegerNotEmpty.StrictIntegerNotEmptyValidator.class}) @ReportAsSingleViolation public @interface ValidateIntegerNotEmpty { String msgArgs() default ""; String message() default "{1001E}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; class StrictIntegerNotEmptyValidator implements ConstraintValidator<ValidateIntegerNotEmpty, Integer> { @Override public boolean isValid(Integer value, ConstraintValidatorContext context) { return !ObjectUtils.isEmpty(value); } } }
1 When the review status is 2 (manual initial review rejection), the review rejection reason is Required item, and the range is 1 to 4
When review If the status is other than 2 (under review or passed manual preliminary review), the reason for review rejection is Non-required items
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <script type="text/javascript" th:src="@{/js/public/jquery-3.6.0.min.js}"></script> <script type="text/javascript" th:src="@{/js/common/common.js}"></script> <title>test7页面</title> </head> <body> <button id="btn">校验数据</button> <h2>我是test7的页面</h2> </body> <script> $("#btn").click(() => { const param1 = { // 人工初审拒绝 auditStatus: 2, // 拒绝的原因 auditRejectReason: 5, }; const url = `http://localhost:8080/test7/groupSequenceProvider`; doAjax(url, param1, function(data) { console.log(data); }); }); </script> </html>
import com.example.jmw.common.validation.ValidateIntegerNotEmpty; import com.example.jmw.form.validation.ValidateTest7FormProvider; import lombok.Data; import org.hibernate.validator.constraints.Range; import org.hibernate.validator.group.GroupSequenceProvider; @Data // 通过该注解所对应的自定义Provider来实现多属性联合校验 @GroupSequenceProvider(ValidateTest7FormProvider.class) public class Test7Form { /** * 1: 审核中 * 2: 人工初审拒绝 * 3: 人工初审通过 */ @ValidateIntegerNotEmpty(msgArgs = "审核状态类型") @Range(min = 1, max = 3, message = "审核拒绝原因:参数传递错误") private Integer auditStatus; /** * 1: 不符合准入要求 * 2: 三方数据拒贷 * 3: 授信额度为0 * 4: 其他 */ @ValidateIntegerNotEmpty(msgArgs = "审核拒绝原因", groups = auditGroup.class) @Range(min = 1, max = 4, message = "审核拒绝原因:参数传递错误", groups = auditGroup.class) private Integer auditRejectReason; // 自定义分组 public interface auditGroup { } }
import com.example.jmw.form.Test7Form; import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider; import org.springframework.util.ObjectUtils; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class ValidateTest7FormProvider implements DefaultGroupSequenceProvider<Test7Form> { @Override public List<Class<?>> getValidationGroups(Test7Form test7Form) { List<Class<?>> defaultGroupSequence = new ArrayList<>(); defaultGroupSequence.add(Test7Form.class); if (ObjectUtils.isEmpty(test7Form)) { return defaultGroupSequence; } // 获取 人工初审 状态 Integer auditStatus = Optional.ofNullable(test7Form.getAuditStatus()).orElse(0) ; // 如果 人工初审通过的话,审核拒绝原因的auditGroup组就会起作用,就变为必填项目,否则为选填项目 if (auditStatus == 2) { defaultGroupSequence.add(Test7Form.auditGroup.class); } return defaultGroupSequence; } }
@Controller @RequestMapping("/test7") public class Test7Controller { @Resource private LocalValidatorFactoryBean validator; @GetMapping("/init") public ModelAndView init() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("test7"); return modelAndView; } @PostMapping("/groupSequenceProvider") @ResponseBody public void groupSequenceProvider(@RequestBody Test7Form form) { Set<ConstraintViolation<Test7Form>> validate = validator.validate(form); for (ConstraintViolation<Test7Form> bean : validate) { // 获取当前的校验信息 String message = bean.getMessage(); System.out.println(message); } } }
##3. Requirements
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <script type="text/javascript" th:src="@{/js/public/jquery-3.6.0.min.js}"></script> <script type="text/javascript" th:src="@{/js/common/common.js}"></script> <title>test7页面</title> </head> <body> <button id="btn">校验数据</button> <h2>我是test7的页面</h2> </body> <script> $("#btn").click(() => { const param2 = { // 领导(2)访问 role: 2, // 权限的数量为5 permissionList: [1, 1, 1, 1, 1], }; const url = `http://localhost:8080/test7/groupSequenceProvider`; doAjax(url, param2, function(data) { console.log(data); }); }); </script> </html>
⏹Form2 to be verified
import com.example.jmw.common.validation.ValidateIntegerNotEmpty; import com.example.jmw.form.validation.ValidateTest7Form1Provider; import lombok.Data; import org.hibernate.validator.constraints.Range; import org.hibernate.validator.group.GroupSequenceProvider; import javax.validation.constraints.Size; import java.util.List; @Data // 通过该注解所对应的自定义Provider来实现多属性联合校验 @GroupSequenceProvider(ValidateTest7Form1Provider.class) public class Test7Form1 { /** * 1: 访客 * 2: 领导 * 3: 管理员 */ @ValidateIntegerNotEmpty(msgArgs = "角色类型") @Range(min = 1, max = 3, message = "错误原因:参数传递错误") private Integer role; @Size.List({ // 访客1个权限 @Size(min = 1, max = 2, message = "访客最多拥有2个权限", groups = GuestGroup.class), // 领导4个权限 @Size(min = 1, max = 4, message = "领导最多拥有4个权限", groups = LeaderGroup.class), // 管理员10个权限 @Size(min = 1, max = 10, message = "管理员最多拥有10个权限", groups = AdminGroup.class) }) private List<Integer> permissionList; // 游客分组 public interface GuestGroup { } // 领导分组 public interface LeaderGroup { } // 管理员分组 public interface AdminGroup { } }
⏹Validator
import com.example.jmw.form.Test7Form1; import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider; import org.springframework.util.ObjectUtils; import java.util.*; public class ValidateTest7Form1Provider implements DefaultGroupSequenceProvider<Test7Form1> { /** * 1: 访客 * 2: 领导 * 3: 管理员 */ private final static List<Integer> roleList = Arrays.asList(1, 2, 3); @Override public List<Class<?>> getValidationGroups(Test7Form1 test7Form1) { List<Class<?>> defaultGroupSequence = new ArrayList<>(); defaultGroupSequence.add(Test7Form1.class); if (ObjectUtils.isEmpty(test7Form1)) { return defaultGroupSequence; } // 获取角色code Integer role = Optional.ofNullable(test7Form1.getRole()).orElse(0) ; if (!roleList.contains(role)) { return defaultGroupSequence; } // 根据角色code,开启相应的组校验 if (role == 1) { defaultGroupSequence.add(Test7Form1.GuestGroup.class); } else if (role == 2) { defaultGroupSequence.add(Test7Form1.LeaderGroup.class); } else if (role == 3) { defaultGroupSequence.add(Test7Form1.AdminGroup.class); } return defaultGroupSequence; } }
⏹ Controller layer performs verification
@Controller @RequestMapping("/test7") public class Test7Controller { @Resource private LocalValidatorFactoryBean validator; @GetMapping("/init") public ModelAndView init() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("test7"); return modelAndView; } @PostMapping("/groupSequenceProvider") @ResponseBody public void groupSequenceProvider(@RequestBody Test7Form1 form) { Set<ConstraintViolation<Test7Form1>> validate = validator.validate(form); for (ConstraintViolation<Test7Form1> bean : validate) { // 获取当前的校验信息 String message = bean.getMessage(); System.out.println(message); } } }
When the role is 2 (leader), there can only be 4 permissions at most, so the verification information is displayed
When When the role is 1 (guest), there are only 2 permissions at most, so the verification information
is displayed. When the role is 3 (administrator), there are 10 at most. Permissions, so there is no verification information
The above is the detailed content of How to use SpringBoot @GroupSequenceProvider annotation to implement bean multi-attribute joint verification. For more information, please follow other related articles on the PHP Chinese website!