hibernate validator【原】

hibernate validator 功能

在开发中经常做一些字段校验的功能,比如非空,长度限制,邮箱验证等等,为了省掉这种冗长繁琐的操作,hibernate validator提供了一套精简的注释方案以实现这些基本校验。

注解说明

Annotation Type

Description   (import javax.validation.constraints.*)

AssertFalse

被注释的元素必须为boolean,且为false

AssertTrue

被注释的元素必须为boolean,且为true

DecimalMax

被注释的元素必须为数字,且小于等于最大值

DecimalMin

被注释的元素必须为数字,且大于等于最小值

Digits

被注释的元素必须为数字,且精度在指定的整数和小数范围内

Future

被注释的元素必须为日期且大于当前时间(是未来的时间)

Max

被注释的元素必须是数字,且小于等于最大值

Min

被注释的元素必须是数字,且大于等于最小值

NotNull

被注释的元素必须不为 null

Null

被注释的元素必须为 null

Past

被注释的元素必须为日期且小于当前时间(是过去的时间)

Pattern

被注释的元素必须字符串,且符合指定正则表达式,如果为null则不校验

Size

被注释的元素必须是字符串,长度大于等于min值,小于等于max值

Annotation Type

Description   (import org.hibernate.validator.constraints.*)

Email

被注释的元素必须是电子邮箱地址

Length

被注释的字符串的大小必须在指定的范围内

NotBlank

被注释的字符串必须非空

NotEmpty

被注释的字符串或列表的必须非空

Range

被注释的元素必须在合适的范围内

URL

被注释的字符串的必须符合url地址格式

使用样例

工具类ValidationTool.java

package hibernate.validator;
import java.util.Set; import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.ValidatorFactory; /**
* HibernateValidator工具
* @author King
*
*/
public class ValidationTool { private static Validator validator; static {
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
validator = vf.getValidator();
} public static <T> void validate(T t) throws ValidationException {
Set<ConstraintViolation<T>> set = validator.validate(t);
if (set.size() > 0) {
StringBuilder errorBuilder = new StringBuilder();
for (ConstraintViolation<T> val : set) {
errorBuilder.append(val.getMessage() + ";");
}
throw new ValidationException(errorBuilder.toString());
}
}
}

学生类Student.java

package hibernate.validator;

import java.util.Date;

import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Future;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import org.hibernate.validator.constraints.URL; /**
* 学生类
*
* @author King
*/
public class Student { @AssertTrue(message = "必须为女孩")
// @AssertFalse(message = "必须为男孩")
Boolean girlFlag; // 以下三者酌情取其一
// 仅针对String,含空白字符的String也是不符合规则的,如" \t "也是不规范的
@NotBlank(message = "名字不能为空")
// 不能为null或者长度为0,可以应用于String类、Collection、Map、数组,(String、Collection、Map的isEmpty()方法)
@NotEmpty(message = "名字不能为空")
// 不能为null
@NotNull(message = "名字不能为空")
String name; @Min(value = 1, message = "年龄不得小于1岁")
@Max(value = 200, message = "年龄不得大于200岁")
Integer age; @Digits(integer = 2, fraction = 2, message = "身高精度为XX.XX米")
Double height; @DecimalMin(value = "3.0", message = "最轻为3.0斤")
@DecimalMax(value = "300.0", message = "最重为300.0斤")
Double weight; // 如果是null则不校验,如果不是null,则校验
@Pattern(regexp = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$", message = "出生日期格式yyyy-MM-dd不正确")
String birthDateStr; // 如果是null则不校验,如果不是null,则校验
@Pattern(regexp = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$", message = "数学考试开始时间格式yyyy-MM-dd HH:mm:ss不正确")
String mathExamTime; @Past(message = "出生日期应为过去时间")
Date birthDate; @Future(message = "毕业时间应为将来时间")
Date graduateDate; @Size(min = 2, max = 20, message = "地址长度必须介于2到20之间")
String address; @Email(message = "邮件格式不合法")
String email; @Length(min = 1, max = 100, message = "兴趣爱好介绍长度必须介于1到100之间")
String hobby; @URL(message = "链接地址不是合法的url")
String link; @Range(min = 0, max = 10, message = "兄弟个数介于0到10个字符之间")
int brotherNumber; String other; // /////////////////////// public static void main(String[] args) {
StudentTest.main(null);
} public int getBrotherNumber() {
return brotherNumber;
} public void setBrotherNumber(int brotherNumber) {
this.brotherNumber = brotherNumber;
} public Boolean getGirlFlag() {
return girlFlag;
} public void setGirlFlag(Boolean girlFlag) {
this.girlFlag = girlFlag;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public Double getHeight() {
return height;
} public void setHeight(Double height) {
this.height = height;
} public Double getWeight() {
return weight;
} public void setWeight(Double weight) {
this.weight = weight;
} public String getBirthDateStr() {
return birthDateStr;
} public void setBirthDateStr(String birthDateStr) {
this.birthDateStr = birthDateStr;
} public String getMathExamTime() {
return mathExamTime;
} public void setMathExamTime(String mathExamTime) {
this.mathExamTime = mathExamTime;
} public Date getBirthDate() {
return birthDate;
} public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
} public Date getGraduateDate() {
return graduateDate;
} public void setGraduateDate(Date graduateDate) {
this.graduateDate = graduateDate;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public String getHobby() {
return hobby;
} public void setHobby(String hobby) {
this.hobby = hobby;
} public String getLink() {
return link;
} public void setLink(String link) {
this.link = link;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public String getOther() {
return other;
} public void setOther(String other) {
this.other = other;
}
}

学生测试类

package hibernate.validator;

import java.util.Date;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory; import org.junit.BeforeClass; import com.isoftstone.pcis.util.ValidationTool; public class StudentTest {
private static Validator validator; /**
* 生成validator校验器
*/
@BeforeClass
public static void setUpValidator() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
} /**
* 验证整个Student
*/ // @Test
// public void test() { public static void main(String[] args) {
Student stu = new Student(); stu.setGirlFlag(true);
stu.setName("Pricess");
stu.setAge(18);
stu.setHeight(1.78d);
stu.setWeight(120.0);
stu.setBirthDateStr("2001-01-06");
stu.setMathExamTime("2018-07-08 09:00:00");
stu.setBirthDate(new Date(System.currentTimeMillis() - 10000));
stu.setGraduateDate(new Date(System.currentTimeMillis() + 100000));
stu.setAddress("浙江杭州");
stu.setEmail("12345 qq.com");//故意不加@,以验证异常效果
stu.setHobby("音乐");
stu.setLink("http://www.cnblogs.com/whatlonelytear/");
stu.setBrotherNumber(1); ValidationTool.validate(stu); } }

运行console打印语句

Exception in thread "main" javax.validation.ValidationException: 邮件格式不合法;
at com.isoftstone.pcis.util.ValidationTool.validate(ValidationTool.java:)
at hibernate.validator.StudentTest.main(StudentTest.java:)

进阶知识

以上hibernate的基本使用已完全可以满足日常需要, 如果有更进一步的规则, 可以参考以下链接(内含自定义规则 spring集成 等)

Hibernate validator使用和自定义validator及整合Spring MVC--https://blog.csdn.net/xulianboblog/article/details/51694924

Spring MVC 数据校验@Valid--https//www.cnblogs.com/happyflyingpig/p/8022881.html

参考链接

java使用validator进行校验--https://blog.csdn.net/dream_broken/article/details/53584169

上一篇:使用spring validation完成数据后端校验-自定义校验的注解-判断是否为空


下一篇:Windows XP系统服役13年今正式退休