数据校验
JSR303
Hibernate Validator
步骤:
一、导入jar 包(注意各jar包之间的版本兼容问题)
classmate.jar
jboss-logging.jar
validation-api.jar
hibernate-validator-annotation-processor.jar
二、配置
<mvc:annotation-driven ></mvc:annotation-driven>
此处 mvc:annotation-driven作用:要实现Hibernate Validator/JRS303 校验(或者其他各种校验),必须实现springmvc提供的接口ValidatorFactory。
LocalValidatorFactoryBean是springmvc提供的一个ValidatorFactory的实现类。
<mvc:annotation-driven ></mvc:annotation-driven>会在springmvc容器中,自动加载一个LocalValidatorFactoryBean类,因此可以直接实现数据校验。
三、使用(加上注解)
a、在需要校验的字段前加入限定注解,如 @Past
@Past //当前时间以前
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;
b、在校验的Controller中,给校验的对象前增加 @Valid
@RequestMapping("testDataTimeFormat")
public String testDataTimeFormat(@Valid Student student,BindingResult result) {
if(result.getErrorCount()>0)
{
for(FieldError error: result.getFieldErrors()){//相当于try ..catch..
System.out.println(error.getDefaultMessage());
}
}
return "info";
}
附录:
Bean Validation 中的 constraint
表 1. Bean Validation 中内置的 constraint
Constraint | 详细信息 |
---|---|
@Null |
被注释的元素必须为 null |
@NotNull |
被注释的元素必须不为 null |
@AssertTrue |
被注释的元素必须为 true |
@AssertFalse |
被注释的元素必须为 false |
@Min(value) |
被注释的元素必须是一个数字,其值必须大于等于指定的最小值 |
@Max(value) |
被注释的元素必须是一个数字,其值必须小于等于指定的最大值 |
@DecimalMin(value) |
被注释的元素必须是一个数字,其值必须大于等于指定的最小值 |
@DecimalMax(value) |
被注释的元素必须是一个数字,其值必须小于等于指定的最大值 |
@Size(max, min) |
被注释的元素的大小必须在指定的范围内 |
@Digits (integer, fraction) |
被注释的元素必须是一个数字,其值必须在可接受的范围内 |
@Past |
被注释的元素必须是一个过去的日期 |
@Future |
被注释的元素必须是一个将来的日期 |
@Pattern(value) |
被注释的元素必须符合指定的正则表达式 |
表 2. Hibernate Validator 附加的 constraint
Constraint | 详细信息 |
---|---|
@Email |
被注释的元素必须是电子邮箱地址 |
@Length |
被注释的字符串的大小必须在指定的范围内 |
@NotEmpty |
被注释的字符串的必须非空 |
@Range |
被注释的元素必须在合适的范围内 |