想搭建基于JSR303的项目环境,你需要如下4个构件:
hibernate-validator-4.2.0.Final.jar
slf4j-api-1.6.1.jar
validation-api-1.0.0.GA.jar
一个简单的POJO,其中采用如下效验规则:
package com.test.request.bean;
import java.util.Date;
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;
public class InfoBean
{
@NotNull(message = "姓名不能为空!")
@Min(value = 1, message = "Id只能大于等于1,小于等于10")
@Max(value = 10, message = "Id只能大于等于1,小于等于10")
private Integer id;
@NotNull(message = "姓名不能为空!")
@Size(min = 2, max = 4, message = "姓名长度必须在{min}和{max}之间")
@Pattern(regexp = "[\u4e00-\u9fa5]+", message = "名称只能输入是中文字符")
private String userName;
@NotNull(message = "密码不能为空!")
@Size(min = 6, max = 12, message = "密码长度必须在{min}和{max}之间")
private String passWord;
@NotNull(message = "日期不能为空!")
@Past(message = "你只能输入过去的提起")
private Date birthday;
@NotNull(message = "邮件不能为空!")
@Email(message = "邮件格式不正确")
private String email;
此处省略set和get方法
}
既然POJO也定义好了,我们还需要使用到ValidatorFactory来获取效验工厂实例,并帮助我们完成基础的效验步骤工作:
package com.test.request.bean;
import java.util.Date;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.Test;
public class InfoBeanTest
{
@Test
public void test() throws Exception
{
/* 创建效验工厂 */
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
/* 信息封装 */
InfoBean infoBean = new InfoBean();
infoBean.setId(-1);
infoBean.setUserName("张三");
infoBean.setPassWord("123456");
infoBean.setEmail("test@test.com");
infoBean.setBirthday(new Date());
/* 将类型装载效验 */
Set<ConstraintViolation<InfoBean>> set = validator.validate(infoBean);
for (ConstraintViolation<InfoBean> constraintViolation : set)
System.out.println("错误:" + constraintViolation.getMessage());
}
}