一、概述

除了依赖注入、方法参数,Bean Validation 1.1定义的功能还包括:

1、分组验证

2、自定义验证规则

3、类级别验证

4、跨参数验证

5、组合多个验证注解

6、其他

二、分组验证

通过分组,可实现不同情况下的不同验证规则,示例如下:

1、定义分组接口

  1. public interface AddView {
    }
  2.  
  3. public interface UpdateView {
    }

2、定义实体

  1. public class Person {
  2. @Null(groups = AddView.class)
  3. @NotNull(groups = {UpdateView.class, Default.class})
  4. private Integer id;
  5. ...
  6. }

  注:不指定分组,即为Default分组

3、业务类

  1. @Service
  2. @Validated
  3. public class PersonService {
  4. @Validated(AddView.class)
  5. public void addPerson(@Valid Person person) {}
  6.  
  7. @Validated({UpdateView.class})
  8. public void updatePerson(@Valid Person person) {}
  9.  
  10. public void defaultOp(@Valid Person person) {}
  11. }

4、测试

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(locations = "classpath:spring-context.xml")
  3. public class ValidTest {
  4. @Autowired
  5. private PersonService testService;
  6.  
  7. @Test(expected = ConstraintViolationException.class)
  8. public void test1() {
  9. Person person = new Person();
  10. person.setId(12);
  11. testService.addPerson(person);
  12. }
  13.  
  14. @Test(expected = ConstraintViolationException.class)
  15. public void test2() {
  16. Person person = new Person();
  17. testService.updatePerson(person);
  18. }
  19.  
  20. @Test(expected = ConstraintViolationException.class)
  21. public void test3() {
  22. Person person = new Person();
  23. testService.defaultOp(person);
  24. }
  25. }

三、自定义验证规则

系统预定义的验证注解不能满足需求时,可自定义验证注解,示例如下:

1、自定义注解

  1. @Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
  2. @Retention(RUNTIME)
  3. @Constraint(validatedBy = ForbiddenValidator.class)
  4. @Documented
  5. public @interface Forbidden {
  6. //默认错误消息
  7. String message() default "{forbidden.word}";
  8.  
  9. //分组
  10. Class<?>[] groups() default { };
  11.  
  12. //负载
  13. Class<? extends Payload>[] payload() default { };
  14.  
  15. //指定多个时使用
  16. @Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
  17. @Retention(RUNTIME)
  18. @Documented
  19. @interface List {
  20. Forbidden[] value();
  21. }
  22. }

2、自定义注解处理类

  1. public class ForbiddenValidator implements ConstraintValidator<Forbidden, String> {
  2. private String[] forbiddenWords = {"admin"};
  3.  
  4. @Override
  5. public void initialize(Forbidden constraintAnnotation) {
  6. //初始化,得到注解数据
  7. }
  8.  
  9. @Override
  10. public boolean isValid(String value, ConstraintValidatorContext context) {
  11. if(StringUtils.isEmpty(value)) {
  12. return true;
  13. }
  14.  
  15. for(String word : forbiddenWords) {
  16. if(value.contains(word)) {
  17. return false;//验证失败
  18. }
  19. }
  20. return true;
  21. }
  22. }

3、默认错误消息

  1. # format.properties
    forbidden.word=包含敏感词汇

4、实体类

  1. public class Person {
  2.   @Forbidden
  3.   private String name;
  4.   ...
  5. }

5、业务类

  1. @Service
  2. @Validated
  3. public class PersonService {
  4. public void defaultOp(@Valid Person person) {
  5.  
  6. }
  7. }

6、测试

  1. @Test(expected = ConstraintViolationException.class)
  2. public void test4() {
  3. Person person = new Person();
  4. person.setName("admin");
  5. testService.defaultOp(person);
  6. }

四、类级别验证

定义类级别验证,可实现对象中的多个属性组合验证,示例如下:

1、定义注解

  1. @Target({ TYPE, ANNOTATION_TYPE})
  2. @Retention(RUNTIME)
  3. @Documented
  4. @Constraint(validatedBy = CheckPasswordValidator.class)
  5. public @interface CheckPassword {
  6. //默认错误消息
  7. String message() default "";
  8.  
  9. //分组
  10. Class<?>[] groups() default { };
  11.  
  12. //负载
  13. Class<? extends Payload>[] payload() default { };
  14.  
  15. //指定多个时使用
  16. @Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
  17. @Retention(RUNTIME)
  18. @Documented
  19. @interface List {
  20. CheckPassword[] value();
  21. }
  22. }

2、定义处理类

  1. public class CheckPasswordValidator implements ConstraintValidator<CheckPassword, Person> {
  2. @Override
  3. public void initialize(CheckPassword constraintAnnotation) {
  4. }
  5.  
  6. @Override
  7. public boolean isValid(Person person, ConstraintValidatorContext context) {
  8. if(person == null) {
  9. return true;
  10. }
  11.  
  12. //没有填密码
  13. if(!StringUtils.isEmpty(person.getNewPassword())) {
  14. context.disableDefaultConstraintViolation();
  15. context.buildConstraintViolationWithTemplate("{password.null}")
  16. .addPropertyNode("password")
  17. .addConstraintViolation();
  18. return false;
  19. }
  20.  
  21. if(!StringUtils.isEmpty(person.getConfirmPassword())) {
  22. context.disableDefaultConstraintViolation();
  23. context.buildConstraintViolationWithTemplate("{password.confirmation.null}")
  24. .addPropertyNode("confirmation")
  25. .addConstraintViolation();
  26. return false;
  27. }
  28.  
  29. //两次密码不一样
  30. if (!person.getNewPassword().equals(person.getConfirmPassword())) {
  31. context.disableDefaultConstraintViolation();
  32. context.buildConstraintViolationWithTemplate("{password.confirmation.error}")
  33. .addPropertyNode("confirmation")
  34. .addConstraintViolation();
  35. return false;
  36. }
  37. return true;
  38. }
  39. }

3、实体

  1. @CheckPassword
  2. public class Person {
  3. private String newPassword;
  4. private String confirmPassword;
  5. ...
  6. }

4、业务类

  1. @Service
  2. @Validated
  3. public class PersonService {
  4. public void checkClassValidation(@Valid Person person) {
  5.  
  6. }
  7. }

5、测试

  1. @Test(expected = ConstraintViolationException.class)
  2. public void test4() {
  3. Person person = new Person();
  4. person.setNewPassword("asd");
  5. person.setConfirmPassword("12132");
  6. testService.checkClassValidation(person);
  7. }

五、跨参数验证

使用跨参数验证,可实现方法级别中的多个参数组合验证,示例如下:

1、定义注解

  1. @Constraint(validatedBy = CrossParameterValidator.class)
  2. @Target({ METHOD, CONSTRUCTOR, ANNOTATION_TYPE })
  3. @Retention(RUNTIME)
  4. @Documented
  5. public @interface CrossParameter {
  6. String message() default "{password.confirmation.error}";
  7. Class<?>[] groups() default { };
  8. Class<? extends Payload>[] payload() default { };
  9. }

2、定义处理类

  1. @SupportedValidationTarget(ValidationTarget.PARAMETERS)
  2. public class CrossParameterValidator implements ConstraintValidator<CrossParameter, Object[]> {
  3. @Override
  4. public void initialize(CrossParameter constraintAnnotation) {
  5. }
  6.  
  7. @Override
  8. public boolean isValid(Object[] value, ConstraintValidatorContext context) {
  9. if(value == null || value.length != 2) {
  10. throw new IllegalArgumentException("must have two args");
  11. }
  12. if(value[0] == null || value[1] == null) {
  13. return true;
  14. }
  15. if(value[0].equals(value[1])) {
  16. return true;
  17. }
  18. return false;
  19. }
  20. }

3、业务类

  1. @Service
  2. @Validated
  3. public class PersonService {
  4. @CrossParameter
  5. public void checkParaValidation(String pw1, String pw2) {
  6.  
  7. }
  8. }

4、测试

  1. @Test(expected = ConstraintViolationException.class)
  2. public void test5() {
  3. testService.checkParaValidation("asd", "123");
  4. }

六、组合多个验证注解

可将多个注解组合成一个注解,示例如下:

1、定义注解

  1. @Target({ FIELD})
  2. @Retention(RUNTIME)
  3. @Documented
  4. @NotNull
  5. @Min(1)
  6. @Constraint(validatedBy = { })
  7. public @interface NotNullMin {
  8. String message() default "";
  9. Class<?>[] groups() default { };
  10. Class<? extends Payload>[] payload() default { };
  11. }

2、实体

  1. public class Person {
  2. @NotNullMin
  3. private Integer id;
  4. ...
  5. }

3、业务类

  1. @Service
  2. @Validated
  3. public class PersonService {
  4. public void checkCompositionValidation(@Valid Person person) {
  5.  
  6. }
  7. }

4、测试

  1. @Test(expected = ConstraintViolationException.class)
  2. public void test6() {
  3. Person person = new Person();
  4. testService.checkCompositionValidation(person);
  5. }

七、其他

Bean Validation 1.1还支持本地化、脚本验证器,详细见参考文档

参考:

Spring4新特性——集成Bean Validation 1.1(JSR-349)到SpringMVC

Spring MVC 使用介绍(十六)数据验证 (三)分组、自定义、跨参数、其他的更多相关文章

  1. Spring MVC 使用介绍(六)—— 注解式控制器(二):请求映射与参数绑定

    一.概述 注解式控制器支持: 请求的映射和限定 参数的自动绑定 参数的注解绑定 二.请求的映射和限定 http请求信息包含六部分信息: ①请求方法: ②URL: ③协议及版本: ④请求头信息(包括Co ...

  2. Spring MVC 使用介绍(十五)数据验证 (二)依赖注入与方法级别验证

    一.概述 JSR-349 (Bean Validation 1.1)对数据验证进一步进行的规范,主要内容如下: 1.依赖注入验证 2.方法级别验证 二.依赖注入验证 spring提供BeanValid ...

  3. Spring MVC 使用介绍(十三)数据验证 (一)基本介绍

    一.消息处理功能 Spring提供MessageSource接口用于提供消息处理功能: public interface MessageSource { String getMessage(Strin ...

  4. Spring MVC 使用介绍(十四)文件上传下载

    一.概述 文件上传时,http请求头Content-Type须为multipart/form-data,有两种实现方式: 1.基于FormData对象,该方式简单灵活 2.基于<form> ...

  5. Spring MVC 使用介绍(十二)控制器返回结果统一处理

    一.概述 在为前端提供http接口时,通常返回的数据需要统一的json格式,如包含错误码和错误信息等字段. 该功能的实现有四种可能的方式: AOP 利用环绕通知,对包含@RequestMapping注 ...

  6. spring(7)--注解式控制器的数据验证、类型转换及格式化

    7.1.简介 在编写可视化界面项目时,我们通常需要对数据进行类型转换.验证及格式化. 一.在Spring3之前,我们使用如下架构进行类型转换.验证及格式化: 流程: ①:类型转换:首先调用Proper ...

  7. Spring MVC—数据绑定机制,数据转换,数据格式化配置,数据校验

    Spring MVC数据绑定机制 数据转换 Spring MVC处理JSON 数据格式化配置使用 数据校验 数据校验 Spring MVC数据绑定机制 Spring MVC解析JSON格式的数据: 步 ...

  8. Spring MVC 3.0 返回JSON数据的方法

    Spring MVC 3.0 返回JSON数据的方法1. 直接 PrintWriter 输出2. 使用 JSP 视图3. 使用Spring内置的支持// Spring MVC 配置<bean c ...

  9. Maven 工程下 Spring MVC 站点配置 (二) Mybatis数据操作

    详细的Spring MVC框架搭配在这个连接中: Maven 工程下 Spring MVC 站点配置 (一) Maven 工程下 Spring MVC 站点配置 (二) Mybatis数据操作 这篇主 ...

  10. MySQL行(记录)的详细操作一 介绍 二 插入数据INSERT 三 更新数据UPDATE 四 删除数据DELETE 五 查询数据SELECT 六 权限管理

    MySQL行(记录)的详细操作 阅读目录 一 介绍 二 插入数据INSERT 三 更新数据UPDATE 四 删除数据DELETE 五 查询数据SELECT 六 权限管理 一 介绍 MySQL数据操作: ...

随机推荐

  1. KOA中间件的基本运作原理

    示例代码托管在:http://www.github.com/dashnowords/blogs 博客园地址:<大史住在大前端>原创博文目录 华为云社区地址:[你要的前端打怪升级指南] 在中 ...

  2. 微信h5 video的问题

    https://blog.csdn.net/hf123lsk/article/details/78920211

  3. 纯CSS编写汉克狗

    1,CSS中原生的变量定义语法是:--*,变量使用语法是:var(--*),其中*表示我们的变量名称:在CSS变量命名中,不能包含$,[,^,(,%等字符,普通字符局限在只要是“数字[0-9]”“字母 ...

  4. JavaScript局部变量变量和函数命名提升

    之前接触了一些javascript局部变量命名提升的问题但是一直没有总结今天特地好好总结一下 变量提升 一个变量的作用域是程序源代码中定义的这个变量的区域.全局变量拥有全局作用域,在javascrip ...

  5. flex 实例 豆瓣手机端布局实现

    0.最终成品

  6. 2.5 Cesium视域分析的实现

    Cesium 视域分析 祝愿周末没事,技术继续分享交流,群685834990

  7. linux 命令基础大全

    pwd:显示当前路径 cd :切换目录 用法:cd cd ../ 切换到上级目录 cd /   切换到根目录 cd ~  (或只有cd )切换到当前用户主目录(home底下以用户名命名的文件夹) /r ...

  8. Linux学习历程——Centos 7 chmod命令

    一.命令介绍 chmod 命令,是Linux管理员最常用的命令之一,用于修改文件或目录的访问权限. Linux系统中,每一个文件都有文件所有者和所属群组,并且规定文件的所有者,所属群组,以及其他人队问 ...

  9. maven中央仓库、远程仓库地址

    1.http://repo1.maven.org/maven2 (官方,速度一般) 2.http://maven.aliyun.com/nexus/content/repositories/centr ...

  10. rank() partition by 排名次

    rank()排名 partition by分组与group by相比各有优势,在这里就省略100字.... 以下为案例: create table student -- 学生表(sid integer ...