本文向大家介绍Hibernate Validator,可能好多人还不了解Hibernate Validator,没有关系,看完本文你肯定有不少收获,希望本文能教会你更多东西。
用Annotations 给类或者类的属性加上约束(constraint),在运行期检查属性值是很优雅的。Hibernate Validator就是这样的一个框架。该框架是十分容易的(就像参考文档中宣称的那样),几乎没有什么学习曲线,Hibernate Validator 是一个验证框架 不需要和Hibernate的其他部分绑定就可以使用,只要在你的项目中添加Hibernate-annotations.jar库就可以了。
那么下面就让我们看看怎么使用吧。
Person.java 类
- /*
- * Created on 2006-1-12 Person.java
- * @author
- */
- package test.annotation.validator;
- import org.hibernate.validator.Length;
- import org.hibernate.validator.Min;
- import org.hibernate.validator.Valid;
- //@Serializability//测试自定义约束
- public class Person {
- private String name;
- private int age;
- private Address address;
- public Person() {}
- @Valid //注意此处
- public Address getAddress() {
- return address;
- }
- public void setAddress(Address address) {
- this.address = address;
- }
- @Min(value = 1)
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- @Length(min = 4)
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
Address.java 类
- /*
- * Created on 2006-1-12 Address.java
- * @author
- */
- package test.annotation.validator;
- import org.hibernate.validator.Length;
- import org.hibernate.validator.Max;
- import org.hibernate.validator.Min;
- public class Address {
- private String street;
- private int num;
- public Address() {}
- @Min(value = 1)
- @Max(value = 100)
- public int getNum() {
- return num;
- }
- public void setNum(int num) {
- this.num = num;
- }
- @Length(min = 3,max = 8)
- public String getStreet() {
- return street;
- }
- public void setStreet(String street) {
- this.street = street;
- }
- }
上面是两个用Hibernate Validator Annotations 注释的类。每个属性都用 约束限制了。
【编辑推荐】