1.创建一个自定义注解
/**
* 实体检验自定义注解类
* @author 李
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidateEntity {
public boolean required() default false;//是否检验null
public boolean requiredLeng() default false;//是否检验长度
public int maxLength() default -1;//最大长度
public int minLength() default -1;//最小长度
public String errorRequiredMsg() default "";//值为null时的错误提示信息
public String errorMinLengthMsg() default "";//最小长度不满足时的提示信息
public String errorMaxLengthMsg() default "";//最大长度不满足时的提示信息
}
2.编写实体类验证工具类
/**
* 验证实体工具类
* @author 李
*/
public class ValidateEntityUtil {
public static JsonResult validate(Object object) {
Field[] declaredFields = object.getClass().getDeclaredFields();
for (Field field : declaredFields) {
ValidateEntity annotation = field.getAnnotation(ValidateEntity.class);
if (annotation != null) {
if (annotation.required()) {
//表示该字段是必填字段
field.setAccessible(true);
try {
Object o = field.get(object);
//首先判断是否为空
if (StringUtils.isEmpty(o)) {
JsonResult jsonResult = JsonResult.CUSTOM_ERROR;
jsonResult.setMsg(annotation.errorRequiredMsg());
return jsonResult;
}
//到这,说明该变量的值不是null
//首先判断是不是String类型
if (o instanceof String) {
//若是字符串类型,则检查其长度
if (annotation.requiredLeng()) {
if (o.toString().length() < annotation.minLength()) {
JsonResult jsonResult = JsonResult.CUSTOM_ERROR;
jsonResult.setMsg(annotation.errorMinLengthMsg());
return jsonResult;
}
if (o.toString().length() > annotation.maxLength()) {
JsonResult jsonResult = JsonResult.CUSTOM_ERROR;
jsonResult.setMsg(annotation.errorMaxLengthMsg());
return jsonResult;
}
}
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return JsonResult.SUCCESS;
}
}
3.实体类使用方式
@ValidateEntity(required = true,requiredLeng = true,errorRequiredMsg="不能为空",maxLength = 10,errorMaxLengthMsg = "超过限制10个字")
private String content;
private Long accountId;
@ValidateEntity(required = true,requiredLeng = true,errorRequiredMsg="不能为空",maxLength = 30,errorMaxLengthMsg = "超过限制30个字")
private String title;
4.编写接口测试
@RequestMapping("test")
JsonResult test(Problem problem){
System.out.println(problem.getContent().length());
System.out.println(problem.getTitle().length());
JsonResult validate = ValidateEntityUtil.validate(problem);
if (validate.getCode()!=1)return validate;
return JsonResult.success(problem);
}
5.测试
版权声明:本文为qq_36732671原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。