https://www.cnblogs.com/cjsblog/p/8946768.html
针对excel导入的一些特殊校验,自定义注解来校验
public @interface FieldValid {
/**
* 校验是否是必须的 默认是
*
* @return
*/
boolean required() default false;
/**
* 错误提示信息
*
* @return
*/
String message() default "";
/**
* 是否包含
*
* @return
*/
String[] containKeys () default {};
/**
* 正则表达式
*
* @return
*/
String pattern() default "";
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 规则注解入口
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface Fieldes {
/**
* 规则集合
*
* @return
*/
FieldValid[] fieldes();
}
public class FieldVerificationUtils {
/**
* 校验字段
*/
public static String checkField(Object object) throws Exception {
String errorMsg = null;
if (object == null) {
return errorMsg;
}
for (Field temp : object.getClass().getDeclaredFields()) {
Fieldes fieldes = temp.getAnnotation(Fieldes.class);
if (fieldes != null) {
FieldValid[] rules = fieldes.fieldes();
String fieldName = temp.getName();
for (FieldValid currentRule : rules) {
Method method = object.getClass().getDeclaredMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length()));
//获取字段值
Object fieldVal = method.invoke(object);
//如果必填
if (currentRule.required() == true) {
if (fieldVal == null || fieldVal=="") {
errorMsg = currentRule.message();
return errorMsg;
}
}
//正则校验
if (StringUtils.isNotBlank(currentRule.pattern())&& fieldVal!=null && fieldVal!="") {
if (!fieldVal.toString().matches(currentRule.pattern())) {
errorMsg = currentRule.message();
return errorMsg;
}
}
//是否包含
if (currentRule.containKeys() != null && currentRule.containKeys().length!=0) {
if(fieldVal!=null && fieldVal!="") {
if (!Arrays.asList(currentRule.containKeys()).contains(fieldVal.toString())) {
errorMsg = currentRule.message();
return errorMsg;
}
}
}
}
}
}
return errorMsg;
}
}
@Data()
public class StaffImportAccountVo {
@Fieldes(fieldes = {@FieldValid(required = true,message = "请填写学号"), @FieldValid(pattern="^[0-9]*$",message="学号格式不正确")})
private String studentNo;
@Fieldes(fieldes = {@FieldValid(required = true,message = "请填写手机号"), @FieldValid(pattern="^[1][3,4,5,6,7,8,9][0-9]{9}$",message="手机号格式不正确")})
private String phone;
@Fieldes(fieldes = {@FieldValid(required = true,message = "请填写岗位类别"), @FieldValid(containKeys= {"实习","正式"},message="职业身份仅能填写实习或正式")})
private String jobIdentityDesc;
}
//调用工具类进行校验
StaffImportAccountDTO dto = new StaffImportAccountDTO();
BeanUtils.copyProperties(object, dto);
String errorMsg= FieldVerificationUtils.checkField(object);
if(StringUtils.isNotBlank(errorMsg)){
log.error("校验不通过")
}