一个简单的办法是在 controller 中用反射校验每一个属性是否都为空,比如:
/**
* 检查是否所有属性都为空
* @
author zifangsky
* @
date 2020/10/29 11:05
* @
since 1.0.0
* @
param element 待处理对象
* @
return 返回 true 表示对象的所有参数都为空
*/
public static <K> boolean checkIfAllFieldsEmpty(K element){
if(element == null){
return true;
}
Class<?> clazz = element.getClass();
//1. 获取当前类及父类的所有属性
List<Field> fieldList = new ArrayList<>();
while (clazz != null){
Field[] declaredFields = clazz.getDeclaredFields();
fieldList.addAll(Arrays.asList(declaredFields));
clazz = clazz.getSuperclass();
}
//2. 统一处理所有符合条件的属性
for (Field field : fieldList) {
//更改权限
field.setAccessible(true);
try {
//对于字符串类型的属性除了要判断是否为空,还要再判断一次是否为空字符串
if(field.getType().isAssignableFrom(String.class)){
String fValue = (String) field.get(element);
if(fValue != null && !"".equals(fValue.trim())){
return false;
}
}else{
Object fValue = field.get(element);
if(fValue != null){
return false;
}
}
}catch (Exception e){
//ignore
}
}
return true;
}
public static void main(String[] args) {
UserForm form1 = new UserForm("张三", "password", 18);
UserForm form2 = new UserForm("", null, null);
System.out.println("检查结果是:" + checkIfAllFieldsEmpty(form1));
System.out.println("检查结果是:" + checkIfAllFieldsEmpty(form2));
}