代码拉取完成,页面将自动刷新
要校验的实体类
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());
}
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。