汉中公司做网站,微网站建设是什么,优秀策划设计网站,如何开发软件?自定义注解校验的实现步骤#xff1a;
1.创建注解类#xff0c;编写校验注解#xff0c;即类似NotEmpty注解 2.编写自定义校验的逻辑实体类#xff0c;编写具体的校验逻辑。(这个类可以实现ConstraintValidator这个接口#xff0c;让注解用来校验) 3.开启使用自定义注解进…自定义注解校验的实现步骤
1.创建注解类编写校验注解即类似NotEmpty注解 2.编写自定义校验的逻辑实体类编写具体的校验逻辑。(这个类可以实现ConstraintValidator这个接口让注解用来校验) 3.开启使用自定义注解进行校验。
第一种实现自定义注解的方式
一、创建注解类
1、创建类时选择Annotation类型 2、编写注解类
编写注解类时需要用到元注解来规定注解的实现方式等
package cn.hsa.bis.api.common.utils;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** Description 基础校验注解* Author chenzz* create 2020/3/6 19:43*/
//Target注解是指定当前自定义注解可以使用在哪些地方这里仅仅让他可以使用在字段上
Target(ElementType.FIELD)
//指定当前注解保留到运行时
Retention(RetentionPolicy.RUNTIME)
public interface ValiInfo {/*** 最小长度*/int minLen() default 0;/*** 最大长度*/int maxLen() default 2147483647;/*** 非空校验*/boolean notBlank() default false;/*** 字典校验*/String codeType() default ;/*** 非法字符校验* 特殊字符ascii码表中除字母、数字外的所有字符顿号、间隔号(·)*/String illegalCharRegExp() default .*[\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f\\u3001\\u00b7].*;/*** 正则校验*/String regexp() default ;/*** 字段含义*/String mean() default ;/*** 汉字校验*/String regexpChinese() default ;
}3、元注解 (编写注解类时必须要明白的)
刚创建出来的注解是不能使用的。因为我们不知道注解应该加在什么地方在什么时间生效所以就引出来元注解的概念。元注解就是注解的注解(有点绕口令的感觉)。专门用来注解注解类型。 java的元注解TargetRetentionDocumentedInherited
Target直接指明了该注解生效的位置该参数没有default值必填。参数是一个枚举类型
Retention指明了注解生效的阶段 Documented 当我们用javaDoc生成API文档时是否将该注解记录到API文档中。 Inherited 这个注解是说我们的注解是否需要被子类继承。是发生在子类和父类之间的一种注解。
注意当我们的注解作用域是Element.TYPE时我们定义在类上的注解可以被子类继承。但是如果我们注解的作用域是Element.METHOD时并且父类的该方法被子类重写那作用在父类的注解不会被子类继承。所以如果我们在接口的方法中定义的注解永远不会被实现类继承因为实现类一定会重写接口中的方法。
二、自定义注解校验逻辑的实现
这里有两种实现方式 一种是当注解仅仅作用在字段(属性)上生效时可以在工具类中编写方法进行逻辑校验 另一种是当注解作用在方法上生效时可以使用Constraint注解指明了校验类进行校验
这里只实现第一种。
第一种当自定义注解仅仅作用在字段上生效时在工具类中编写方法进行逻辑校验(在工作中用的比较多)
public class ToolUtils {/*** 对象基础格式校验针对带有valiInfo注解的属性* param obj* param ignoreFields 忽略校验的字段* return: java.lang.StringBuffer* author: chenzz* date: 2020/4/22 23:36*/public static StringBuffer valiObjStringField(Object obj, String[] ignoreFields) {StringBuffer errMsg new StringBuffer();try {SetString ignoreFieldSet new HashSet();ignoreFieldSet.add(class);if (null ! ignoreFields) {for (String field : ignoreFields) {if (StringUtils.isNotBlank(field)) {ignoreFieldSet.add(field);}}}PropertyDescriptor[] propertyDescriptors BeanUtils.getPropertyDescriptors(obj.getClass());for (PropertyDescriptor targetPd : propertyDescriptors) {if (ignoreFieldSet.contains(targetPd.getName())) {continue;}Method readMethod targetPd.getReadMethod();if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {readMethod.setAccessible(true);}Object value readMethod.invoke(obj);ValiInfo valiInfo obj.getClass().getDeclaredField(targetPd.getName()).getAnnotation(ValiInfo.class);if (null valiInfo) {continue;}String mean valiInfo.mean();if (StringUtils.isBlank(mean)) {mean targetPd.getName();}// 空置校验boolean isBlank null value || StringUtils.isBlank(value.toString());if (valiInfo.notBlank()) {if (isBlank) {errMsg.append(String.format(【%s】不能为空, mean));continue;}} else {if (isBlank) {continue;}}// 如果是字符串才进行下面的校验if (!(value instanceof String)) {continue;}String strValue value.toString();// 长度校验 最小长度为0int len strValue.length();if (len valiInfo.minLen()) {errMsg.append(String.format(【%s%s】长度不能小于%d个字符, mean, strValue, valiInfo.minLen()));continue;}// 最大长度为2147483647if (len valiInfo.maxLen()) {errMsg.append(String.format(【%s%s】长度不能超过%d个字符, mean, strValue, valiInfo.maxLen()));Method writeMethod targetPd.getWriteMethod();if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {writeMethod.setAccessible(true);}writeMethod.invoke(obj, strValue.substring(0, valiInfo.maxLen() - 1));continue;}if (strValue.matches(valiInfo.illegalCharRegExp())) {errMsg.append(String.format(【%s%s】中不能包含特殊字符, mean, strValue));continue;}if (StringUtils.isNotBlank(valiInfo.regexp()) !strValue.matches(valiInfo.regexp())) {errMsg.append(String.format(【%s%s】格式校验不通过, mean, strValue));continue;}// 校验是否存在汉字if (StringUtils.isNotBlank(valiInfo.regexpChinese())) {char c[] strValue.toCharArray();Pattern pattern Pattern.compile(valiInfo.regexpChinese());boolean flag false;for (int i 0; i c.length; i) {Matcher matcher pattern.matcher(String.valueOf(c[i]));if (matcher.matches()) {flag true;}}if (flag) {errMsg.append(String.format(【%s%s】入参存在汉字, mean, strValue));continue;}}// 码值校验if (StringUtils.isNotBlank(valiInfo.codeType())) {if (DictUtil.isNotDict(valiInfo.codeType().toUpperCase(), strValue)) {errMsg.append(String.format(【%s%s】不在代码表中, mean, strValue));}}}return errMsg;} catch (IllegalAccessException e) {throw new BisException(BusinessConst.CALL_FAIL_TYPE_JC, 对象数据格式校验失败!);} catch (InvocationTargetException e) {throw new BisException(BusinessConst.CALL_FAIL_TYPE_JC, 对象数据格式校验失败!);} catch (NoSuchFieldException e) {throw new BisException(BusinessConst.CALL_FAIL_TYPE_JC, 对象数据格式校验失败!);}}
}三、使用自定义注解
自定义校验注解在代码中的应用
1、在dto中使用
Data
public class PsnInsureInfoQueryDTO implements Serializable {private static final long serialVersionUID -3173331123860803536L;/*** 缴费开始年月*/ValiInfo(mean 缴费开始, minLen 6, maxLen 6, regexp RegexpConst.REGEXP_YM)private String begnYm;/*** 单位编号*/ValiInfo(mean 单位编号, minLen 1, maxLen 40, illegalCharRegExp RegexpConst.ILLEGAL_CHAR_REGEXP_EMPNO, regexpChinese RegexpConst.REGEXP_CHINESE)private String empNo;/*** 险种类型*/ValiInfo(mean 险种类型, minLen 1, maxLen 3, codeType INSUTYPE, regexpChinese RegexpConst.REGEXP_CHINESE)private String insutype;/*** 统筹区编码*/ValiInfo(mean 统筹区编码, minLen 6, maxLen 6, codeType ADMDVS_PLC, regexpChinese RegexpConst.REGEXP_CHINESE)private String poolarea;/*** 参保状态*/ValiInfo(mean 参保状态, minLen 1, maxLen 3, codeType PSN_INSU_STAS, regexpChinese RegexpConst.REGEXP_CHINESE)private String psnInsuStas;/*** 人员编号*/ValiInfo(mean 人员编号, minLen 1, maxLen 36, notBlank true, regexpChinese RegexpConst.REGEXP_CHINESE, illegalCharRegExp RegexpConst.ILLEGAL_CHAR_REGEXP_PSNNO)private String psnNo;
}2、在代码中通过调用valiObjStringField方法来进行校验
//control层的方法
public ResultVO insertHmcYcx(RequestBody HmcinfoDTO hmcinfoDTO){//.......其它逻辑//调用方法进行自定义注解的校验String errorMsg ToolUtils.valiObjStringField(hmcinfoDTO).toString();if (StringUtils.isNotBlank(errorMsg)) {log.info(errorMsg);return new ResultVO(errorMsg);}//.......其它逻辑ResultVO vo hmcBPO.insertHmc(hmcinfoDTO);return vo;
}