Java BeanValidation

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.0.GA.jar、hibernate-validator-4.2.0.Final.jar、slf4j-api-1.6.1.jar。

Order类:

package com.zzj.beanvalidation;

import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

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 com.zzj.beanvalidation;

import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotEmpty;

public class Receiver {
	@NotEmpty(message = "国家不能空")
	private String Country;
	private String CountryCode;
	@NotNull(message = "邮箱不能为空")
	@org.hibernate.validator.constraints.Email(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 com.zzj.beanvalidation;

import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

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 com.zzj.beanvalidation;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值