5 Star 5 Fork 0

一把斯噶 / 数据校验框架

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 2.82 KB
一键复制 编辑 原始数据 按行查看 历史
huangzl 提交于 2018-12-11 11:55 . 新增校验注解

数据校验框架

一个简单的数据校验框架,不依赖任何第三方jar

使用示例:

要校验的实体类

public class ObjectRequireEntiry {

    @NotBlank()
    @Name("生日")
    @DateFormat("yyyy-MM-dd")
    private String birthday;    

    @Name("手机号码")
    @Phone
    private String phone;  

    @Name("身高")
    @Max(230)
    @Min(1)
    private Integer stature;        


    @Name("体重")
    @Max(200)
    @Min(1)
    private Integer weight;         
  

    @Name("对象要求")
    @Length(min=0,max=200)
    private String require_back;
    
    get...
    set...
    
}

校验

ValidateResult result = AnnotationValidator.validate(objectRequireEntiry);
if(!result.isValid()){
    map.put("msg",result.getMessage());
    map.put("field",result.getFieldName());
    return map;
}

可用注解


DateFormat:时间格式化
Length:长度限制
Max:最大数字
Min:最小数字
Name:属性名称(主要是用于向前端提示错误时,显示的属性名)
NotBlank:不允许为空
Phone:手机号码校验

自定义扩展


1.继承IAnnotationParser接口并重写validate方法,实现自己的校验判断
2.向AnnotationValidator类的vList中添加自己的扩展类

与mvc框架集成

新增拦截器或使用AOP方式获取action的入参,判断是否存在@Validate注解,并根据注解的值判断是返回json数据还是在保存在request作用域中让前端显示
1.在方法的参数中添加@Validate注解

@ResponseBody
public Object add(@Validate User user){

}

2.新增拦截器或AOP拦截action的参数,注解判断代码:

if(field.isAnnotationPresent(Validate.class)){      //判断是否使用了Validate注解
    for (Annotation annotation : field.getDeclaredAnnotations()) {    //获取所有注解
        if(annotation.annotationType().equals(Validate.class) ){      //如果是Validate注解
            ValidateResult result = AnnotationValidator.validate(objectRequireEntiry);
            if(((Validate)annotation).validType() == ValidType.JSON){   
                if(!result.isValid()){  //校验失败
                    //将错误信息以json格式返回给前端
                    map.put("msg",result.getMessage());
                    map.put("field",result.getFieldName());
                }
            }else{
                if(!result.isValid()){  //校验失败
                    //将错误信息保存在qurest作用域中,返回给页面
                    request.setAttribute("msg",result.getMessage());
                    request.setAttribute("field",result.getFieldName());
                }
            }
        }
    }
}
Java
1
https://gitee.com/weiyiee/data_checking_framework.git
git@gitee.com:weiyiee/data_checking_framework.git
weiyiee
data_checking_framework
数据校验框架
master

搜索帮助