Chinaunix首页 | 论坛 | 博客
  • 博客访问: 518196
  • 博文数量: 135
  • 博客积分: 3568
  • 博客等级: 中校
  • 技术积分: 1942
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-19 17:52
文章分类

全部博文(135)

文章存档

2012年(29)

2011年(41)

2010年(26)

2009年(12)

2008年(9)

2007年(12)

2006年(6)

分类: Java

2011-03-21 13:51:50

正学习Spring 3,发现其中的validation使用了JSR303的RI实现,这为何物?如何使用?抱着疑问,写个例子瞅瞅先。
 TestJSR303.rar  

ValidationMessages.properties
  1. me.test.Pattern.message=必须匹配正则表达式 "{regexp}"
  2. me.test.NotNull.message=不能为null
  3. me.test.Min.message=必须大于等于{value}
  4. me.test.Max.message=必须小于等于{value}
  5. me.test.Size.message=长度必须位于{min}{max}之间

Person.java
  1. package me.test;

  2. import javax.validation.constraints.Max;
  3. import javax.validation.constraints.Min;
  4. import javax.validation.constraints.NotNull;
  5. import javax.validation.constraints.Pattern;
  6. import javax.validation.constraints.Size;

  7. public class Person {

  8.     @Pattern(regexp = "^U\\d{3}$", message = "{me.test.Pattern.message}")
  9.     private String id;

  10.     @NotNull(message = "用户名不能为null")
  11.     private String name;

  12.     @Min(value = 1, message = "{me.test.Min.message}")
  13.     @Max(value = 150)
  14.     private Integer age;

  15.     @Size(min = 5, max = 10, message = "地址长度不能为>={min} && <=10")
  16.     private String address = null;

  17.     // getter && setter
  18. }

PersonTest.java
  1. package me.test;

  2. import java.util.ResourceBundle;
  3. import java.util.Set;

  4. import javax.validation.Configuration;
  5. import javax.validation.ConstraintViolation;
  6. import javax.validation.Validation;
  7. import javax.validation.Validator;
  8. import javax.validation.ValidatorFactory;

  9. import junit.framework.TestCase;

  10. import org.hibernate.validator.engine.ResourceBundleMessageInterpolator;
  11. import org.junit.Before;
  12. import org.junit.Test;

  13. /**
  14.  * 什么是JSR303-Bean Validation?
  15.  * 是一套类似于Apache Commons Validator,但是可以通过注解进行配置,
  16.  * 也可以通过XML文件进行配置。
  17.  *
  18.  *
  19.  * 参考实现:
  20.  * Hibernate Validator
  21.  *
  22.  *
  23.  * 注意:
  24.  * Hibernate Validator 4.2.0.Beta2版本的压缩包中包含中文的文档,在线看时总#¥@的被连接重置。
  25.  * 但这个工程里我使用的是 4.1.0.Final 版
  26.  *
  27.  * 小结:
  28.  * 1. 缺少一些感觉比较常用的Validate,
  29.  * 比如,对字符串类型的日期格式验证。
  30.  * 假如一个字段是"yyyyMMdd"格式的年月日字符串,
  31.  * 可以通过@Pattern用正则表达式限定为全部为字符串,
  32.  * 可是用户仍能发送"20011299" 或 "20010231"这样不存在的日期。
  33.  * JSR303中只提供了@Past,@Future以对java.util.Date和java.util.Calendar
  34.  * 验证其是否是过去/将来的时间。
  35.  *
  36.  * 比如,如果要保证某个字符串的长队必须为某个固定的值,这时可以使用@Size,
  37.  * 但是@Size是用来保证长度在一个区域内的,有个min和max,
  38.  * 若把min和max设为某个固定值,则消息不太合适。
  39.  *
  40.  * 2. 该规范以及RI实现中只能够对单个字段进行Validate,没有类似Struts中使用的 validateWhen.
  41.  * 若是能够提供一个使用EL表达式的类似实现就好了。
  42.  * 也许这种验证应该拿到业务里进行验证吧?使用Spring的Validator?
  43.  *
  44.  * RI实现中又扩展了4个注解:@Email,@Length,@NotEmpty,@Range
  45.  * 其中@Length与规范中定义的@Size类似,但仅仅适用于string类型,而@Size则不限于String,还可以用于Collection,Map,Array
  46.  *
  47.  * 工程目录树:
  48.  * /
  49.  * |- src
  50.  * |   | ValidationMessages.properties
  51.  * |   |- me
  52.  * |      |- test
  53.  * |           Person.java
  54.  * |           PersonTest.java
  55.  * |- lib:
  56.  *      hibernate-validator-4.0.1.GA.jar
  57.  *      jpa-api-2.0.Beta-20090815.jar
  58.  *      log4j-1.2.14.jar
  59.  *      slf4j-api-1.5.6.jar
  60.  *      slf4j-log4j12-1.5.6.jar
  61.  *      validation-api-1.0.0.GA.jar
  62.  *      junit-4.6.jar
  63.  *
  64.  * @author btpka3@163.com
  65.  *
  66.  */
  67. public class PersonTest {

  68.     private Validator validator = null;

  69.     @Before
  70.     public void setUp() {
  71.         if (validator == null) {
  72.             // Configuration config = Validation.byDefaultProvider().configure();
  73.             // config.messageInterpolator(new ResourceBundleMessageInterpolator(ResourceBundle.getBundle("me.test.ValidationMessages") ));
  74.             // validator = config.buildValidatorFactory().getValidator();
  75.             ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
  76.             validator = validatorFactory.getValidator();
  77.         }
  78.     }

  79.     /**
  80.      * 正常 - 全部检验通过
  81.      */
  82.     @SuppressWarnings("unchecked")
  83.     @Test
  84.     public void test001() {
  85.         // ■ 准备环境
  86.         // ■ 准备参数
  87.         Person p = new Person();
  88.         p.setId("U001");
  89.         p.setName("zhang3");
  90.         p.setAge(25);
  91.         p.setAddress("abcdefg");
  92.         // ■ 执行
  93.         Set<ConstraintViolation<Person>> violations = validator.validate(p);
  94.         // ■ 验证结果
  95.         ConstraintViolation<Person>[] arr = violations.toArray(new ConstraintViolation[0]);
  96.         TestCase.assertEquals(0, arr.length);
  97.         // ■ 验证环境
  98.     }

  99.     /**
  100.      * 异常 - id格式不正确
  101.      */
  102.     @SuppressWarnings("unchecked")
  103.     @Test
  104.     public void test002() {
  105.         // ■ 准备环境
  106.         // ■ 准备参数
  107.         Person p = new Person();
  108.         p.setId("U00X");
  109.         p.setName("zhang3");
  110.         p.setAge(25);
  111.         p.setAddress("abcdefg");
  112.         // ■ 执行
  113.         Set<ConstraintViolation<Person>> violations = validator.validate(p);
  114.         // ■ 验证结果
  115.         ConstraintViolation<Person>[] arr = violations.toArray(new ConstraintViolation[0]);
  116.         TestCase.assertEquals(1, arr.length);
  117.         ConstraintViolation<Person> violation = arr[0];
  118.         String propertyPath = violation.getPropertyPath().toString();
  119.         TestCase.assertEquals("id", propertyPath);
  120.         String message = violation.getMessage();
  121.         TestCase.assertEquals("必须匹配正则表达式 \"^U\\d{3}$\"", message);
  122.         // ■ 验证环境
  123.     }

  124.     /**
  125.      * 异常 - name == null
  126.      */
  127.     @SuppressWarnings("unchecked")
  128.     @Test
  129.     public void test003() {
  130.         // ■ 准备环境
  131.         // ■ 准备参数
  132.         Person p = new Person();
  133.         p.setId("U001");
  134.         p.setName(null);
  135.         p.setAge(25);
  136.         p.setAddress("abcdefg");
  137.         // ■ 执行
  138.         Set<ConstraintViolation<Person>> violations = validator.validate(p);
  139.         // ■ 验证结果
  140.         ConstraintViolation<Person>[] arr = violations.toArray(new ConstraintViolation[0]);
  141.         TestCase.assertEquals(1, arr.length);
  142.         ConstraintViolation<Person> violation = arr[0];
  143.         String propertyPath = violation.getPropertyPath().toString();
  144.         TestCase.assertEquals("name", propertyPath);
  145.         String message = violation.getMessage();
  146.         TestCase.assertEquals("用户名不能为null", message);
  147.         // ■ 验证环境
  148.     }

  149.     /**
  150.      * 异常 - age值的范围不正确(0)
  151.      */
  152.     @SuppressWarnings("unchecked")
  153.     @Test
  154.     public void test004() {
  155.         // ■ 准备环境
  156.         // ■ 准备参数
  157.         Person p = new Person();
  158.         p.setId("U001");
  159.         p.setName("zhang3");
  160.         p.setAge(0);
  161.         p.setAddress("abcdefg");
  162.         // ■ 执行
  163.         Set<ConstraintViolation<Person>> violations = validator.validate(p);
  164.         // ■ 验证结果
  165.         ConstraintViolation<Person>[] arr = violations.toArray(new ConstraintViolation[0]);
  166.         TestCase.assertEquals(1, arr.length);
  167.         ConstraintViolation<Person> violation = arr[0];
  168.         String propertyPath = violation.getPropertyPath().toString();
  169.         TestCase.assertEquals("age", propertyPath);
  170.         String message = violation.getMessage();
  171.         TestCase.assertEquals("必须大于等于1", message);
  172.         // ■ 验证环境
  173.     }

  174.     /**
  175.      * 异常 - age值的范围不正确(200)
  176.      */
  177.     @SuppressWarnings("unchecked")
  178.     @Test
  179.     public void test005() {

  180.         // ■ 准备环境
  181.         // ■ 准备参数
  182.         Person p = new Person();
  183.         p.setId("U001");
  184.         p.setName("zhang3");
  185.         p.setAge(200);
  186.         p.setAddress("abcdefg");
  187.         // ■ 执行
  188.         Set<ConstraintViolation<Person>> violations = validator.validate(p);
  189.         // ■ 验证结果
  190.         ConstraintViolation<Person>[] arr = violations.toArray(new ConstraintViolation[0]);
  191.         TestCase.assertEquals(1, arr.length);
  192.         ConstraintViolation<Person> violation = arr[0];
  193.         String propertyPath = violation.getPropertyPath().toString();
  194.         TestCase.assertEquals("age", propertyPath);
  195.         String message = violation.getMessage();
  196.         TestCase.assertEquals("must be less than or equal to 150", message);
  197.         // ■ 验证环境
  198.     }

  199.     /**
  200.      * 异常 - address长度不正确(3)
  201.      */
  202.     @SuppressWarnings("unchecked")
  203.     @Test
  204.     public void test006() {

  205.         // ■ 准备环境
  206.         // ■ 准备参数
  207.         Person p = new Person();
  208.         p.setId("U001");
  209.         p.setName("zhang3");
  210.         p.setAge(25);
  211.         p.setAddress("abc");
  212.         // ■ 执行
  213.         Set<ConstraintViolation<Person>> violations = validator.validate(p);
  214.         // ■ 验证结果
  215.         ConstraintViolation<Person>[] arr = violations.toArray(new ConstraintViolation[0]);
  216.         TestCase.assertEquals(1, arr.length);
  217.         ConstraintViolation<Person> violation = arr[0];
  218.         String propertyPath = violation.getPropertyPath().toString();
  219.         TestCase.assertEquals("address", propertyPath);
  220.         String message = violation.getMessage();
  221.         TestCase.assertEquals("地址长度不能为>=5 && <=10", message);
  222.         // ■ 验证环境
  223.     }
  224. }

阅读(2334) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~