请求参数非空校验
写项目的时候请求参数有时候有好几十个字段都要做非空校验,挨个写if难免有点显low,写个通用工具类,任何接口的请求参数需要做非空校验的时候都能用。
思路
- 方法需要传入一个requestMap和一个数组。
- requestMap是你的请求参数,数组里面包含的是你需要对哪些字段进行校验。
- 程序会将Map的key取出来,然后和你传入的数组进行对比,请求参数中不存在的元素将会被提示出来。
代码
import com.google.common.base.Strings;
import java.util.*;
/**
* @author ChenJinyu
*/
public class CheckUtils {
/**
* 非空校验主要方法
*
* @param requestMap 请求参数
* @param columnArr 需要校验的字段的数组
* @return map中包含了错误信息,可自定义
*/
public static Map<String, String> nullCheck(Map<String, Object> requestMap, String[] columnArr) {
List<String> columnList = Arrays.asList(columnArr);
List<String> columnMatchList = new ArrayList<>();
requestMap.keySet().iterator().forEachRemaining(key -> {
if (columnList.contains(key)) {
columnMatchList.add(key);
}
});
Map<String, String> resultMap = new HashMap<>(4);
StringBuffer resultMessage = new StringBuffer();
List<String> different = getDifferent(columnList, columnMatchList);
if (different.size() > 0) {
resultMessage.append("以下字段不能为空:( ");
for (String nullColumn : different) {
resultMessage.append(nullColumn).append(", ");
}
resultMessage.deleteCharAt(resultMessage.length() - 2).append(")");
}
if (resultMessage.length() > 0) {
resultMap.put("error_message", resultMessage.toString());
}
return resultMap;
}
/**
* 两个数组找不同
*
* @param listA 与listB随意传,不分先后
* @param listB 与listA随意传,不分先后
* @return 两个数组中不同的元素
*/
private static List<String> getDifferent(List<String> listA, List<String> listB) {
List<String> differentArr = new ArrayList<>();
List<String> maxList = listA;
List<String> minList = listB;
if (listB.size() > listA.size()) {
maxList = listB;
minList = listA;
}
Map<String, String> map = new HashMap<>(maxList.size());
maxList.iterator().forEachRemaining(maxKey -> map.put(maxKey, "1"));
minList.iterator().forEachRemaining(minKey -> {
if (!Strings.isNullOrEmpty(map.get(minKey))) {
map.put(minKey, "2");
return;
}
differentArr.add(minKey);
});
map.entrySet().iterator().forEachRemaining(entry -> {
if ("1".equals(entry.getValue())) {
differentArr.add(entry.getKey());
}
});
return differentArr;
}
}
测试
public static void main(String[] args) {
String[] checkArr = {"aaa","bbb","ccc","ddd"};
Map<String,Object> requestMap = new HashMap<>(8);
requestMap.put("aaa","123");
requestMap.put("bbb","234");
requestMap.put("ccc","345");
Map<String, String> resultMap = nullCheck(requestMap, checkArr);
System.out.println(resultMap.get("error_message"));
}
结果:
以下字段不能为空:( ddd )