package com.merchant.util; 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; import com.modules.api.vo.PacketOrderDetailInfo; import com.modules.api.vo.PacketOrderInfo; /** * hibernate Validator校验工具类 * @author zhangmingyue * */ public class ValidatorUtil { private static ValidatorFactory factory; public static Validator validator; public static void init() { factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } public static void clean() { factory.close(); } public static void main(String[] args) { init(); PacketOrderInfo info = new PacketOrderInfo(); List<PacketOrderDetailInfo> items = new ArrayList<PacketOrderDetailInfo>(); PacketOrderDetailInfo item = new PacketOrderDetailInfo(); items.add(item); info.setItems(items); //info.setRev_tel("手机号"); Set<ConstraintViolation<PacketOrderInfo>> set = validator.validate(info); for (ConstraintViolation<PacketOrderInfo> c : set) { System.out.println(c.getMessageTemplate()); return; } clean(); } }
import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.Valid; import java.io.Serializable; public class PacketOrderInfo implements Serializable { /** * 订单编号 */ @NotBlank(message="订单编号不能为空") private String ordero; /** * 商品信息 * 注意:@Valid,无该注解,无法加载出该对象内属性校验 */ @Valid @NotEmpty(message="商品信息不能为空") private List<PacketOrderDetailInfo> items = new ArrayList<PacketOrderDetailInfo>(); }