分組序列@GroupSequenceProvider、@GroupSequence控制資料校驗順序,解決多字段聯合邏輯校驗問題
#Hibernate Validator提供了非標準的
@GroupSequenceProvider註解
。針對目前物件實例的狀態,動態來決定載入那些校驗組進入預設校驗組。
需要藉助Hibernate Validation提供給我們的DefaultGroupSequenceProvider介面
來處理那些屬性在什麼情況下進入指定的分組。
⏹自訂校驗數值不能為空的註解
@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 當審核狀態為2(人工初審拒絕)的時候,審核拒絕原因為
必填項<!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); } } }
當參數auditStatus為2(人工初審拒絕)時,auditRejectReason(審核拒絕原因)為必填項,因此顯示出校驗資訊
當參數auditStatus為3(人工初審通過)時,auditRejectReason(審核拒絕原因)為非必填項,因此無校驗失敗訊息
############三.需求############2 當遊客(1)造訪時,最多有2個權限############當領導(2)存取,最多有4個權限############當管理員(3)存取,最多有10個權限############⏹前台###<!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>
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 { } }
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 @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); } } }
以上是怎麼使用SpringBoot @GroupSequenceProvider註解實作bean多屬性聯合校驗的詳細內容。更多資訊請關注PHP中文網其他相關文章!