Java BeanValidation

时间:2025-03-12 09:14:34

JSR(Java Specification Requests,Java规范提案) 303 – Bean Validation 是一个数据验证的规范,2009 年 11 月确定最终方案。2009 年 12 月 Java EE 6 发布,Bean Validation 作为一个重要特性被包含其中。

Hibernate Validator 是 Bean Validation 的参考实现 . Hibernate Validator 提供了 JSR 303 规范中所有内置 constraint 的实现,除此之外还有一些附加的 constraint。

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 被注释的元素必须在合适的范围内
有些时候,在用户的应用中需要一些更复杂的 constraint。Bean Validation 提供扩展 constraint 的机制。可以通过两种方法去实现,一种是组合现有的 constraint 来生成一个更复杂的 constraint,另外一种是开发一个全新的 constraint。

示例

所需Jar包:validation-api-1.0.、hibernate-validator-4.2.、slf4j-api-1.6.。

Order类:

package ;

import ;

import ;
import ;
import ;

public class Order {
	@NotNull(message = "订单号不能为空 ") 
	@Size(max = 11, message = "订单号长度不能超过11")
	private String PlatformOrderID;
	@Valid // 级联验证
	private Receiver Receiver;
	@Valid // 级联验证
	private List<Product> ProductList;

	public String getPlatformOrderID() {
		return PlatformOrderID;
	}

	public void setPlatformOrderID(String platformOrderID) {
		PlatformOrderID = platformOrderID;
	}

	public Receiver getReceiver() {
		return Receiver;
	}

	public void setReceiver(Receiver receiver) {
		Receiver = receiver;
	}

	public List<Product> getProductList() {
		return ProductList;
	}

	public void setProductList(List<Product> productList) {
		ProductList = productList;
	}

}
Receiver类:
package ;

import ;

import ;

public class Receiver {
	@NotEmpty(message = "国家不能空")
	private String Country;
	private String CountryCode;
	@NotNull(message = "邮箱不能为空")
	@(message = "邮箱格式不正确")
	private String Email;

	public String getCountry() {
		return Country;
	}

	public void setCountry(String country) {
		Country = country;
	}

	public String getCountryCode() {
		return CountryCode;
	}

	public void setCountryCode(String countryCode) {
		CountryCode = countryCode;
	}

	public String getEmail() {
		return Email;
	}

	public void setEmail(String email) {
		Email = email;
	}
	
}
Product类:
package ;

import ;
import ;
import ;

public class Product {
	@NotNull(message = "英文品名不能为空")
	private String CustomsName;
	private String CustomsCnName;
	@DecimalMin(value = "0", message = "申报价值不能小于0")
	private String DeclareValue;
	@Pattern(regexp = "\\d", message = "数量不合法") // 正则验证
	private String Quantity;

	public String getCustomsName() {
		return CustomsName;
	}

	public void setCustomsName(String customsName) {
		CustomsName = customsName;
	}

	public String getCustomsCnName() {
		return CustomsCnName;
	}

	public void setCustomsCnName(String customsCnName) {
		CustomsCnName = customsCnName;
	}

	public String getDeclareValue() {
		return DeclareValue;
	}

	public void setDeclareValue(String declareValue) {
		DeclareValue = declareValue;
	}

	public String getQuantity() {
		return Quantity;
	}

	public void setQuantity(String quantity) {
		Quantity = quantity;
	}

}
测试:
package ;

import ;
import ;
import ;

import ;
import ;
import ;
import ;

public class Test {
	public static void main(String[] args) throws Exception {
		ValidatorFactory vf = ();
		Validator validator = ();
		Order order = new Order();
		("111111111111111"); // 不合法的订单长度
		
		Receiver receiver = new Receiver();
		("dddd"); // 不合法的邮箱
		(receiver);
		
		List<Product> products = new ArrayList<Product>();
		Product product = new Product();
		("1.0"); // 不合法的数量
		("-1"); // 不合法的申报价值
		(product);
		(products);
		
		Set<ConstraintViolation<Order>> validate = (order);
		for (ConstraintViolation<Order> cv : validate) {
			(() + "(" + () + ")"
					+ "-->" + ());
		}
	}
}
结果:
申报价值不能小于0(ProductList[0].DeclareValue)-->-1
数量不合法(ProductList[0].Quantity)-->1.0
订单号长度不能超过11(PlatformOrderID)-->111111111111111
国家不能空()-->null
邮箱格式不正确()-->dddd
英文品名不能为空(ProductList[0].CustomsName)-->null