java使用validator进行校验

article/2025/10/6 21:23:05
不管是html页面表单提交的对象数据还是和第三方公司进行接口对接,都需要对接收到的数据进行校验(非空、长度、格式等等)。如果使用if一个个进行校验(字段非常多),这是让人崩溃的过程。幸好jdk或hibernate都提供了对object对象的校验,只需加上相应的注解即可。

     本人喜欢学习时,都建立个maven小项目进行实践学习。

1.项目建立


pom.xml

[html] view plain copy
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  2.   <modelVersion>4.0.0</modelVersion>  
  3.   <groupId>com.fei</groupId>  
  4.   <artifactId>validation-test</artifactId>  
  5.   <version>0.0.1-SNAPSHOT</version>  
  6.     
  7.   <dependencies>  
  8.     
  9.     <dependency>  
  10.         <groupId>javax.el</groupId>  
  11.         <artifactId>javax.el-api</artifactId>  
  12.         <version>2.2.4</version>  
  13.     </dependency>  
  14.       
  15.   <dependency>  
  16.         <groupId>org.hibernate</groupId>  
  17.         <artifactId>hibernate-validator</artifactId>  
  18.         <version>5.1.3.Final</version>  
  19.     </dependency>  
  20.     
  21.   </dependencies>  
  22.     
  23.     
  24. </project>  
  是用来练手的

2.基本校验练习

StudentInfo.java

[java] view plain copy
  1. package com.fei.info;  
  2.   
  3. import javax.validation.constraints.Pattern;  
  4.   
  5. import org.hibernate.validator.constraints.NotBlank;  
  6.   
  7. public class StudentInfo {  
  8.   
  9.     @NotBlank(message="用户名不能为空")  
  10.     private String userName;  
  11.       
  12.     @NotBlank(message="年龄不能为空")  
  13.     @Pattern(regexp="^[0-9]{1,2}$",message="年龄是整数")  
  14.     private String age;  
  15.       
  16.     /** 
  17.      * 如果是空,则不校验,如果不为空,则校验 
  18.      */  
  19.     @Pattern(regexp="^[0-9]{4}-[0-9]{2}-[0-9]{2}$",message="出生日期格式不正确")  
  20.     private String birthday;  
  21.       
  22.     @NotBlank(message="学校不能为空")  
  23.     private String school;  
  24.   
  25.     public String getUserName() {  
  26.         return userName;  
  27.     }  
  28.   
  29.     public void setUserName(String userName) {  
  30.         this.userName = userName;  
  31.     }  
  32.   
  33.     public String getAge() {  
  34.         return age;  
  35.     }  
  36.   
  37.     public void setAge(String age) {  
  38.         this.age = age;  
  39.     }  
  40.   
  41.     public String getBirthday() {  
  42.         return birthday;  
  43.     }  
  44.   
  45.     public void setBirthday(String birthday) {  
  46.         this.birthday = birthday;  
  47.     }  
  48.   
  49.     public String getSchool() {  
  50.         return school;  
  51.     }  
  52.   
  53.     public void setSchool(String school) {  
  54.         this.school = school;  
  55.     }  
  56. }  
ValidatorUtil.java

[java] view plain copy
  1. package com.fei.util;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5. import java.util.Set;  
  6.   
  7. import javax.validation.ConstraintViolation;  
  8. import javax.validation.Validation;  
  9. import javax.validation.Validator;  
  10. import javax.validation.groups.Default;  
  11.   
  12. public class ValidatorUtil {  
  13.     private static Validator validator = Validation.buildDefaultValidatorFactory()  
  14.             .getValidator();  
  15.       
  16.     public static <T> Map<String,StringBuffer> validate(T obj){  
  17.         Map<String,StringBuffer> errorMap = null;  
  18.         Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);  
  19.         if(set != null && set.size() >0 ){  
  20.             errorMap = new HashMap<String,StringBuffer>();  
  21.             String property = null;  
  22.             for(ConstraintViolation<T> cv : set){  
  23.                 //这里循环获取错误信息,可以自定义格式  
  24.                 property = cv.getPropertyPath().toString();  
  25.                 if(errorMap.get(property) != null){  
  26.                     errorMap.get(property).append("," + cv.getMessage());  
  27.                 }else{  
  28.                     StringBuffer sb = new StringBuffer();  
  29.                     sb.append(cv.getMessage());  
  30.                     errorMap.put(property, sb);  
  31.                 }  
  32.             }  
  33.         }  
  34.         return errorMap;  
  35.     }  
  36.   
  37.      
  38. }  
ValidatorTest.java

[java] view plain copy
  1. package com.fei;  
  2.   
  3. import java.util.Map;  
  4.   
  5. import com.fei.info.StudentInfo;  
  6. import com.fei.util.ValidatorUtil;  
  7.   
  8. public class ValidatorTest {  
  9.   
  10.     public static void main(String[] args) {  
  11.         StudentInfo s = new StudentInfo();  
  12.         long startTime = System.currentTimeMillis();  
  13.         print(ValidatorUtil.validate(s));  
  14.         System.out.println("===============耗时(毫秒)=" + (System.currentTimeMillis() - startTime));  
  15.           
  16.         s.setUserName("小明");  
  17.         s.setAge("a10");  
  18.         s.setBirthday("2016-9-1");  
  19.         startTime = System.currentTimeMillis();  
  20.         print(ValidatorUtil.validate(s));  
  21.         System.out.println("===============耗时(毫秒)=" + (System.currentTimeMillis() - startTime));  
  22.           
  23.           
  24.           
  25.     }  
  26.       
  27.     private static void print(Map<String,StringBuffer> errorMap){  
  28.         if(errorMap != null){  
  29.             for(Map.Entry<String, StringBuffer> m : errorMap.entrySet()){  
  30.                 System.out.println(m.getKey() + ":" + m.getValue().toString());  
  31.             }  
  32.         }  
  33.     }  
  34. }  

来看看运行结果:

[plain] view plain copy
  1. 十二月 12, 2016 4:02:00 下午 org.hibernate.validator.internal.util.Version <clinit>  
  2. INFO: HV000001: Hibernate Validator 5.1.3.Final  
  3. school:学校不能为空  
  4. age:年龄不能为空  
  5. userName:用户名不能为空  
  6. ===============耗时(毫秒)=280  
  7. birthday:出生日期格式不正确  
  8. school:学校不能为空  
  9. age:年龄是整数  
  10. ===============耗时(毫秒)=3  
   看到运行结果,心中一喜,达到了我们的要求。


   看StudentInfo中的import发现注解的来源有来自javax和hibernate。

javax中有





hibernate中有



  如果现有的校验规则都不满足,则可以自定义校验规则

3.自定义校验规则

Money.java

[plain] view plain copy
  1. package com.fei.validator;  
  2.    
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.    
  8. import javax.validation.Constraint;  
  9. import javax.validation.Payload;  
  10.    
  11.    
  12. @Target({ElementType.FIELD, ElementType.METHOD})  
  13. @Retention(RetentionPolicy.RUNTIME)  
  14. @Constraint(validatedBy=MoneyValidator.class)  
  15. public @interface Money {  
  16.      
  17.     String message() default"不是金额形式";  
  18.      
  19.     Class<?>[] groups() default {};  
  20.      
  21.     Class<? extends Payload>[] payload() default {};  
  22.    
  23. }  

MoneyValidator.java

[plain] view plain copy
  1. package com.fei.validator;  
  2.    
  3. import java.util.regex.Pattern;  
  4.    
  5. import javax.validation.ConstraintValidator;  
  6. import javax.validation.ConstraintValidatorContext;  
  7.    
  8.    
  9. public class MoneyValidator implements ConstraintValidator<Money, Double> {  
  10.    
  11.     private String moneyReg = "^\\d+(\\.\\d{1,2})?$";//表示金额的正则表达式  
  12.     private Pattern moneyPattern = Pattern.compile(moneyReg);  
  13.      
  14.     public void initialize(Money money) {  
  15.        // TODO Auto-generated method stub  
  16.         
  17.     }  
  18.    
  19.     public boolean isValid(Double value, ConstraintValidatorContext arg1) {  
  20.        if (value == null)  
  21.            //金额是空的,返回true,是因为如果null,则会有@NotNull进行提示  
  22.            //如果这里false的话,那金额是null,@Money中的message也会进行提示  
  23.            //自己可以尝试  
  24.            return true;  
  25.        return moneyPattern.matcher(value.toString()).matches();  
  26.     }  
  27.    
  28. }  

StudentInfo.java

加上,注意因为money是Double,所以不能用@NotBlank,因为@NotBlank是对字符串校验的

[plain] view plain copy
  1. @NotNull(message="金额不能为空")  
  2.     @Money(message="金额格式不正确")  
  3.     private Double money;  

ValidatorTest.java

[plain] view plain copy
  1. package com.fei;  
  2.   
  3. import java.util.Map;  
  4.   
  5. import com.fei.info.StudentInfo;  
  6. import com.fei.util.ValidatorUtil;  
  7.   
  8. public class ValidatorTest {  
  9.   
  10.     public static void main(String[] args) {  
  11.         StudentInfo s = new StudentInfo();  
  12.         long startTime = System.currentTimeMillis();  
  13.         print(ValidatorUtil.validate(s));  
  14.         System.out.println("===============耗时(毫秒)=" + (System.currentTimeMillis() - startTime));  
  15.           
  16.         s.setUserName("小明");  
  17.         s.setAge("a10");  
  18.         s.setBirthday("2016-9-1");  
  19.         s.setMoney(100.00001);  
  20.         startTime = System.currentTimeMillis();  
  21.         print(ValidatorUtil.validate(s));  
  22.         System.out.println("===============耗时(毫秒)=" + (System.currentTimeMillis() - startTime));  
  23.           
  24.           
  25.           
  26.     }  
  27.       
  28.     private static void print(Map<String,StringBuffer> errorMap){  
  29.         if(errorMap != null){  
  30.             for(Map.Entry<String, StringBuffer> m : errorMap.entrySet()){  
  31.                 System.out.println(m.getKey() + ":" + m.getValue().toString());  
  32.             }  
  33.         }  
  34.     }  
  35. }  
运行结果:

[plain] view plain copy
  1. 十二月 12, 2016 4:42:41 下午 org.hibernate.validator.internal.util.Version <clinit>  
  2. INFO: HV000001: Hibernate Validator 5.1.3.Final  
  3. school:学校不能为空  
  4. age:年龄不能为空  
  5. money:金额不能为空  
  6. userName:用户名不能为空  
  7. ===============耗时(毫秒)=280  
  8. birthday:出生日期格式不正确  
  9. school:学校不能为空  
  10. age:年龄是整数  
  11. money:金额格式不正确  
  12. ===============耗时(毫秒)=4  

  当然,如果你的项目使用springMVC或structs2,都会对应的集成方法。

4.级联校验

  如果校验的对象中包含另一个对象信息时,校验也要同时校验另一个对象,则可以使用@Valid

ParentInfo.java

[plain] view plain copy
  1. package com.fei.info;  
  2.   
  3. import org.hibernate.validator.constraints.NotBlank;  
  4.   
  5. public class ParentInfo {  
  6.   
  7.     @NotBlank(message="父亲名称不能为空")  
  8.     private String fatherName;  
  9.       
  10.     @NotBlank(message="母亲名称不能为空")  
  11.     private String motherName;  
  12.   
  13.     public String getFatherName() {  
  14.         return fatherName;  
  15.     }  
  16.   
  17.     public void setFatherName(String fatherName) {  
  18.         this.fatherName = fatherName;  
  19.     }  
  20.   
  21.     public String getMotherName() {  
  22.         return motherName;  
  23.     }  
  24.   
  25.     public void setMotherName(String motherName) {  
  26.         this.motherName = motherName;  
  27.     }  
  28. }  
StudentInfo.java

中加入,set,get是必须的

[plain] view plain copy
  1. /**  
  2.      * 如果不加@NotNull,则prentInfo=null时,不会对ParentInfo内的字段进行校验  
  3.      */  
  4.     @NotNull(message="父母信息不能为空")  
  5.     @Valid  
  6.     private ParentInfo parentInfo;  
ValidatorTest.java

[java] view plain copy
  1. package com.fei;  
  2.   
  3. import java.util.Map;  
  4.   
  5. import com.fei.info.ParentInfo;  
  6. import com.fei.info.StudentInfo;  
  7. import com.fei.util.ValidatorUtil;  
  8.   
  9. public class ValidatorTest {  
  10.   
  11.     public static void main(String[] args) {  
  12.         StudentInfo s = new StudentInfo();  
  13.         long startTime = System.currentTimeMillis();  
  14.         print(ValidatorUtil.validate(s));  
  15.         System.out.println("===============耗时(毫秒)=" + (System.currentTimeMillis() - startTime));  
  16.           
  17.         s.setUserName("小明");  
  18.         s.setAge("a10");  
  19.         s.setBirthday("2016-9-1");  
  20.         s.setMoney(100.00001);  
  21.         s.setParentInfo(new ParentInfo());  
  22.         startTime = System.currentTimeMillis();  
  23.         print(ValidatorUtil.validate(s));  
  24.         System.out.println("===============耗时(毫秒)=" + (System.currentTimeMillis() - startTime));  
  25.           
  26.           
  27.           
  28.     }  
  29.       
  30.     private static void print(Map<String,StringBuffer> errorMap){  
  31.         if(errorMap != null){  
  32.             for(Map.Entry<String, StringBuffer> m : errorMap.entrySet()){  
  33.                 System.out.println(m.getKey() + ":" + m.getValue().toString());  
  34.             }  
  35.         }  
  36.     }  
  37. }  

运行结果:

[plain] view plain copy
  1. 十二月 12, 2016 4:56:16 下午 org.hibernate.validator.internal.util.Version <clinit>  
  2. INFO: HV000001: Hibernate Validator 5.1.3.Final  
  3. parentInfo:父母信息不能为空  
  4. school:学校不能为空  
  5. age:年龄不能为空  
  6. money:金额不能为空  
  7. userName:用户名不能为空  
  8. ===============耗时(毫秒)=285  
  9. birthday:出生日期格式不正确  
  10. school:学校不能为空  
  11. parentInfo.fatherName:父亲名称不能为空  
  12. age:年龄是整数  
  13. parentInfo.motherName:母亲名称不能为空  
  14. money:金额格式不正确  
  15. ===============耗时(毫秒)=9  

转自:https://blog.csdn.net/dream_broken/article/details/53584169

http://chatgpt.dhexx.cn/article/LVtHk1C0.shtml

相关文章

java validator_Spring中校验器(Validator)的深入讲解

前言 Spring框架的 validator 组件,是个辅助组件,在进行数据的完整性和有效性非常有用,通过定义一个某个验证器,即可在其它需要的地方,使用即可,非常通用。 应用在执行业务逻辑之前,必须通过校验保证接受到的输入数据是合法正确的,但很多时候同样的校验出现了多次,在不…

springboot使用hibernate validator校验

目录 一、参数校验二、hibernate validator校验demo三、hibernate的校验模式 1、普通模式&#xff08;默认是这个模式&#xff09;2、快速失败返回模式四、hibernate的两种校验 1、请求参数校验2、GET参数校验(RequestParam参数校验)3、model校验4、对象级联校验5、分组校验五…

Validator 使用总结

介绍 首先说下大家常用的hibernate-validator&#xff0c;它是对JSR-303/JSR-349标准的实现&#xff0c;然后spring为了给开发者提供便捷集成了hibernate-validator&#xff0c;默认在springmvc模块。 依赖 本文所介绍皆在springboot应用的基础上&#xff0c;首先加上web模块…

浅谈 Android Tombstone(墓碑日志)分析步骤

最近项目产品刚刚出货&#xff0c;客户退机、死机事件频发。日常解决bug中&#xff0c;少不了和墓碑日志打交道&#xff0c;截止今天之前&#xff0c;见到墓碑日志都是一脸懵逼&#xff0c;不知道怎么分析。最近又有了两个日志&#xff0c;硬着头皮看吧。之所以称之为浅谈&…

Android tombstone文件是如何生成的

本节内容我们聚焦到androidQ上&#xff0c;分析android中一个用于debug的功能&#xff0c;那就是tombstone&#xff0c;俗称“墓碑”。现实生活中墓碑一般是给死人准备的&#xff0c;而在android系统中“墓碑”则是给进程准备的。 为何Android要设计出这样一个东西呢&#xff…

【Android NDK 开发】NDK C/C++ 代码崩溃调试 - Tombstone 报错信息日志文件分析 ( 获取 tombstone_0X 崩溃日志信息 )

文章目录 一、崩溃信息描述二、手机命令行操作三、电脑命令行操作四、Tombstone 内容 Tombstone 报错信息日志文件被保存在了 /data/tombstones/ 目录下 , 先 ROOT 再说 , 没有 ROOT 权限无法访问该目录中的信息 ; 使用 Pixel 2 手机进行调试 , 其它 ROOT 后的手机也可以使用 …

Android tombstone 分析案例

Android tombstone 分析案例 tombstone文件内容1. 体系结构2. 发生Crash线程3. 原因4. 寄存器状态4.1 处理器工作模式下的寄存器4.2 未分组寄存器r0 – r74.3 分组寄存器r8 – r144.4 程序计数器pc(r15)4.5 程序状态寄存器4.6 ARM参数规则 5. 回溯栈6. 程序栈7. 寄存器地址附近…

RocksDB Tombstone 详解

目录 为什么会有墓碑&#xff1f; 使用场景 原理 描述 分段 查询 优化点 总结 为什么会有墓碑&#xff1f; 我们知道 TP 数据库一般选择 KV 引擎作为存储引擎&#xff0c;数据库的元数据和数据通过一定的编码规则变成 KV 对存储在存储引擎中&#xff0c;比如 CockroachD…

Tombstone 文件分析

Tombstone 文件分析 /* * 下面信息是dropbox负责添加的 **/ isPrevious: true Build: Rock/odin/odin:7.1.1/NMF26F/1500868195:user/dev-keys Hardware: msm8953 Revision: 0 Bootloader: unknown Radio: unknown Kernel: Linux version 3.18.31-perf-g34cb3d1 (smartcmhardc…

android Tombstone 流程

一 总述 下面是一份dump 的log&#xff1a; 810 876 I system_server: libdebuggerd_client: started dumping process 678 740 740 I /system/bin/tombstoned: registered intercept for pid 678 and type kDebuggerdNativeBacktrace 678 678 I libc : Requested du…

android tombstone log分析

今天和大家一起聊聊android 中出现的 Tombstone问题&#xff0c;近期在定制pad 上分析设备概率性重启&#xff0c;导出bugreport日志后&#xff0c;除了看到anr log外&#xff0c;同级目录下还看到了tombstones 并且对比以往日志&#xff0c;发现都生产了大量tombstone...,于是…

深入学习tombstone和signal

三驾马车&#xff08;CPU&#xff0c;内存和存储设备&#xff09;中&#xff0c;跑得最慢的就是存储设备了 电脑上&#xff0c;从HDD 到SSD&#xff0c;从SATA SSD到PCIe SSD&#xff0c;硬盘是越来越快&#xff1b; 手机上&#xff0c;从SD卡&#xff0c;到eMMC卡&#xff0…

tombstone

1.什么是tombstone 当一个动态库&#xff08;native 程序&#xff09;开始执行时&#xff0c;系统会注册一些连接到 debuggerd 的 signal handlers&#xff0c;当系统 crash 的时候&#xff0c;会保存一个 tombstone 文件到/data/tombstones目录下&#xff08;Logcat中也会有相…

Tombstone原理分析

本文主要围绕三个问题对tombstone进行分析和介绍&#xff0c;debuggerd是如何监控进程并生成tombstone的&#xff1f;tombstone文件中的信息都是什么&#xff0c;是怎么获取的&#xff1f;tombstone文件应该怎么分析&#xff1f; 一、Tombstone简介 当一个native程序开始执行时…

【date】Linux date命令修改时间的问题

Linux date命令修改时间的问题 问题路径找原因解决方法 问题 Android10&#xff1b;高通平台 使用下面date命令修改时间日期&#xff0c;时分秒生效&#xff0c;年月日不生效 > date -D YYYY-MM-DD hh:mm:ss 路径 \android\external\toybox\toys\posix\date.c \android\e…

i2ctools工具移植到android(使用NDK方式 在某android平台测试)

前提条件 主板i2c已在设备树配置status和引脚复用正常&#xff0c;即设备的i2c总线达到正常使用条件I2C device interface假设内核已配置进去 编译工具链NDK环境搭建 下载NDK 下载地址点我解压 ~/workspace/ndk$ ls android-ndk-r22b android-ndk-r22b-linux-x86_64.zip …

高通平台 Android9 adb shell “hwclock -w“ 报错

hwclock -w 报错 文章目录 hwclock -w 报错问题现象分析1. hwclock命令分析2. /dev/rtc0驱动节点分析 修改设备树后hwclock -w报错没有了&#xff0c;但是系统会重启&#xff0c;原因未知 问题现象 sdm660_64:/ # hwclock -w hwclock: ioctl 4024700a: Invalid argument分析 …

Android top命令、ps命令、busybox命令

top命令 usage: top [-Hbq] [-k FIELD,] [-o FIELD,] [-s SORT] [-n NUMBER] [-m LINES] [-d SECONDS] [-p PID,] [-u USER,]Show process activity in real time.-H Show threads -k Fallback sort FIELDS (default -S,-%CPU,-ETIME,-PID) -o Show FIELDS (def PID,USER,PR,N…

OpenHarmony啃论文俱乐部—盘点开源鸿蒙引用的三方开源软件[1]

目录这里写自定义目录标题 OpenHarmony third_party三方库&#xff1a;学术研究和参与开源的结合third_party_openh264third_party_ninjathird_party_gnthird_party_markupsafethird_party_toyboxthird_party_gstreamerthird_party_ffmpegthird_party_mtdevthird_party_flutter…

Android缺少awk工具的几种解决方法

在日常测试中&#xff0c;我们会用到各种各样的Android平台&#xff0c;用于测试存储设备的性能。其中&#xff0c;我们依赖到Android平台自身的工具&#xff0c;通过编写shell脚本来实现测试存储设备的性能。   而awk工具(shell命令)在shell脚本中会经常用到&#xff0c;一般…