提示:文末提供demo项目下载!!!
一、hibernate validate项目创建
二、hibernate validate依赖说明
$title(pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo-manual-validate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo-manual-validate</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
重点配置:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
三、hibernate validate验证工具编写
$title(ValidateUtils.java)
package com.example.demomanualvalidate.util;
import org.springframework.util.StringUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
public class ValidateUtils {
public static String validate(Object obj) {
// 用于存储验证后的错误信息
StringBuffer buffer = new StringBuffer(64);
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
if (obj!=null&& obj instanceof Collection){
Collection collection=(Collection)obj;
for (Object ob:collection){
String res=validate(ob);
if (!StringUtils.isEmpty(res)){
buffer.append(res);
buffer.append(",");
}
}
}
//对象字段中含有集合的处理
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field:fields){
field.setAccessible(true);
Object fv=getFieldValueByName(field.getName(),obj);
if (fv!=null&&fv instanceof Collection){
String res=validate(fv);
if (!StringUtils.isEmpty(res)){
buffer.append(res);
buffer.append(",");
}
}
}
// 验证某个对象,其实也可以只验证其中的某一个属性的
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);
Iterator<ConstraintViolation<Object>> iter = constraintViolations.iterator();
while (iter.hasNext()) {
String message = iter.next().getMessage()+",";
buffer.append(message);
}
if(buffer.length()>0)
return buffer.toString().substring(0, buffer.toString().length()-1);
return buffer.toString();
}
/**
* 根据属性名获取属性值
* */
public static Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return value;
} catch (NoSuchMethodException e){
// System.out.println("验证字段get方法未找到");
return null;
} catch (InvocationTargetException e) {
//忽略方法内部错误
return null;
} catch (Exception e) {
throw new RuntimeException("验证过程获取属性值错误",e);
}
}
}
四、hibernate validate验证数据模型创建
$title(DogFood.java)
package com.example.demomanualvalidate.model;
import javax.validation.constraints.NotEmpty;
/**
* 狗粮
*/
public class DogFood {
@NotEmpty(message = "狗粮名称不能为空")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
$title(Dog.java)
package com.example.demomanualvalidate.model;
import javax.validation.constraints.NotNull;
import java.util.List;
public class Dog {
public Dog(String name) {
this.name = name;
}
@NotNull(message = "宠物名称不能为空")
private String name;
private List<DogFood> foods;
public List<DogFood> getFoods() {
return foods;
}
public void setFoods(List<DogFood> foods) {
this.foods = foods;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
$title(Persion.java)
package com.example.demomanualvalidate.model;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
public class Persion {
public Persion(String name, List<Dog> dogs) {
this.name = name;
this.dogs = dogs;
}
@NotEmpty(message = "用户名不能为空")
private String name;
@NotNull(message = "必须有宠物狗")
private List<Dog> dogs;//拥有的宠物狗
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Dog> getDogs() {
return dogs;
}
public void setDogs(List<Dog> dogs) {
this.dogs = dogs;
}
}
五、hibernate validate验证测试
$title(Test.java)
package com.example.demomanualvalidate;
import com.example.demomanualvalidate.model.Dog;
import com.example.demomanualvalidate.model.DogFood;
import com.example.demomanualvalidate.model.Persion;
import com.example.demomanualvalidate.util.ValidateUtils;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
//-----0
Persion p0=new Persion("", null);
String failValue=ValidateUtils.validate(p0);
System.out.println("错误信息0:"+failValue);
Dog d1=new Dog(null);
Persion p1=new Persion("", Arrays.asList(new Dog[]{d1}));
failValue=ValidateUtils.validate(p1);
System.out.println("错误信息1:"+failValue);
//-----2
DogFood df=new DogFood();
d1.setFoods(Arrays.asList(new DogFood[]{df}));
Persion p2=new Persion("", Arrays.asList(new Dog[]{d1}));
failValue=ValidateUtils.validate(p2);
System.out.println("错误信息2:"+failValue);
//---GOOD
Dog d=new Dog("阿三");
Persion p=new Persion("小左",Arrays.asList(new Dog[]{d}));
failValue=ValidateUtils.validate(p);
System.out.println("错误信息:"+failValue);
}
}
执行结果截图:
从输出结果来看,已经实现了hibernate validate树形验证,有任何问题欢迎下方评论区留言讨论。
项目下载地址 :demo-manual-validate.zip
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/243613.html