spring boot 参数校验

spring boot 参数校验,第1张

spring boot 参数校验 @NotEmpty、@NotBlank、@NotNull 区别和使用

首先需要说明下,本提到的 @NotEmpty、@NotBlank、@NotNull 分别是
javax.validation.constraints.NotEmpty、javax.validation.constraints.NotBlank 、javax.validation.constraints.NotNull。

通过注解的方式我们可以更加优雅的对参数的格式进行校验,但是在使用 @NotEmpty、@NotBlank、@NotNull 的过程中,由于含义有点类似,所以导致使用的时候会有一些迷茫,下面,对这三个注解逐一进行使用上的说明:

@NotNull
适用于基本数据类型(Integer,Long,Double等等),当 @NotNull 注解被使用在 String 类型的数据上,则表示该数据不能为 Null(但是可以为 Empty)
@NotBlank
适用于 String 类型的数据上,加了@NotBlank 注解的参数不能为 Null 且 trim() 之后 size > 0
@NotEmpty
适用于 String、Collection集合、Map、数组等等,加了@NotEmpty 注解的参数不能为 Null 或者 长度为 0
在使用这些注解的时候,还需要注意一点(注:否则会造成注解无效哦!!),那就是在Controller 层定义方法的时候在参数位置上加上 @Valid(javax.validation.Valid) 注解!!!如下图:



这两个参数必须挨着,否则会报错400

Utils工具类

public class Utils {
    private static Logger log = LoggerFactory.getLogger(Utils.class);
    public static ObjectMapper mapper = new ObjectMapper();

    public Utils() {
    }

    public static String toJSONString(Object obj) {
        if (null == obj) {
            return null;
        } else {
            try {
                return mapper.writevalueAsString(obj);
            } catch (JsonProcessingException var2) {
                log.error("系统异常:", var2);
                return null;
            }
        }
    }

    public static void info(Object info) {
        try {
            System.out.println(mapper.writevalueAsString(info));
        } catch (Exception var2) {
            log.error("系统异常:", var2);
        }

    }

    public static void info(Logger log, String info, Object... objs) {
        try {
            String[] strs = new String[objs.length];

            for(int i = 0; i < objs.length; ++i) {
                Object o = objs[i];
                strs[i] = mapper.writevalueAsString(o);
            }

            log.info(info, strs);
        } catch (Exception var6) {
            log.error("系统异常:", var6);
        }

    }

    public static String getReturnErrors(List list) {
        Map fieldErrors = new HashMap();
        Iterator var2 = list.iterator();

        String key;
        while(var2.hasNext()) {
            ObjectError fieldError = (ObjectError)var2.next();
            key = fieldError.getCode();
            String msg = fieldError.getDefaultMessage();
            if (fieldErrors.containsKey(key)) {
                fieldErrors.put(key, (String)fieldErrors.get(key) + "," + msg);
            } else {
                fieldErrors.put(key, msg);
            }
        }

        List fileErrorsList = new ArrayList();
        if (CollectionUtils.isNotEmpty(fieldErrors.keySet())) {
            Iterator var7 = fieldErrors.keySet().iterator();

            while(var7.hasNext()) {
                key = (String)var7.next();
                fileErrorsList.add(fieldErrors.get(key));
            }
        }

        return StringUtils.join((Iterable)fileErrorsList.stream().distinct().collect(Collectors.toList()), ";");
    }

    public static String getReturnFieldErrors(List fieldErrorList) {
        Map fieldErrors = new HashMap();
        Iterator var2 = fieldErrorList.iterator();

        String key;
        while(var2.hasNext()) {
            FieldError fieldError = (FieldError)var2.next();
            key = fieldError.getField();
            String msg = fieldError.getDefaultMessage();
            if (fieldErrors.containsKey(key)) {
                fieldErrors.put(key, (String)fieldErrors.get(key) + "," + msg);
            } else {
                fieldErrors.put(key, msg);
            }
        }

        List fileErrorsList = new ArrayList();
        if (CollectionUtils.isNotEmpty(fieldErrors.keySet())) {
            Iterator var7 = fieldErrors.keySet().iterator();

            while(var7.hasNext()) {
                key = (String)var7.next();
                fileErrorsList.add(fieldErrors.get(key));
            }
        }

        return StringUtils.join((Iterable)fileErrorsList.stream().distinct().collect(Collectors.toList()), ";");
    }

    public static  Map buildMap(Object... objs) {
        Map map = new HashMap();

        for(int i = 0; i < objs.length; ++i) {
            int j = i + 1;
            map.put(objs[i], objs[j]);
            ++i;
        }

        return map;
    }

    public static void main(String[] args) {
        Map map = buildMap("k", "b", "a", new Date());
        System.out.println(JSONUtils.toJson(map));
    }

    public static  List buildList(T... objs) {
        List list = new ArrayList();

        for(int i = 0; i < objs.length; ++i) {
            list.add(objs[i]);
        }

        return list;
    }

    public static String urlReplace(String url, Object... objs) {
        if (StringUtils.isNotBlank(url) && null != objs && objs.length > 0) {
            for(int i = 0; i < objs.length; ++i) {
                url = url.replace("{" + i + "}", String.valueOf(objs[i]));
            }
        }

        return url;
    }

    public static String listConcat(List contents) {
        StringBuffer s = new StringBuffer();
        Iterator var2 = contents.iterator();

        while(var2.hasNext()) {
            String str = (String)var2.next();
            s.append(str);
        }

        return s.toString();
    }

    public static String fileNameFilter(String fileName, boolean allReplace) {
        String leftStr = "";
        String rightStr = "";
        String prefxStr = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        fileName = fileName.substring(0, fileName.lastIndexOf(prefxStr));
        if (!allReplace) {
            if (fileName.contains("/")) {
                leftStr = fileName.substring(0, fileName.lastIndexOf("/") + 1);
                rightStr = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
            } else {
                rightStr = fileName;
            }
        } else {
            rightStr = fileName;
        }

        rightStr = rightStr.replaceAll("[^A-Za-z\u4e00-\u9fa5]*", "");
        fileName = leftStr + rightStr + "-" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + prefxStr;
        return fileName;
    }

    public static  List> subToPageData(List list, int pageSize) {
        List> dataList = new ArrayList();
        if (CollectionUtils.isEmpty(list)) {
            return dataList;
        } else {
            int pageNum = 0;
            int startIndex = false;
            int endIndex = false;
            int totalRows = list.size();

            for(int totalPage = (int)Math.ceil(Double.valueOf((double)totalRows) / (double)pageSize); pageNum < totalPage; ++pageNum) {
                int startIndex = pageNum * pageSize;
                int endIndex = (pageNum + 1) * pageSize;
                endIndex = endIndex >= totalRows ? totalRows : endIndex;
                List pojos = list.subList(startIndex, endIndex);
                dataList.add(pojos);
            }

            return dataList;
        }
    }

    public static String listToString(List inspecterDeptNames, String separator) {
        StringBuffer buffer = new StringBuffer();
        if (org.springframework.util.CollectionUtils.isEmpty(inspecterDeptNames)) {
            return buffer.toString();
        } else {
            for(int i = 0; i < inspecterDeptNames.size(); ++i) {
                if (i != 0) {
                    buffer.append(",");
                }

                buffer.append((String)inspecterDeptNames.get(i));
                buffer.append(separator);
            }

            return buffer.toString();
        }
    }

    public static String generateSixNum() {
        String sources = "0123456789";
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();

        for(int j = 0; j < 6; ++j) {
            flag.append(sources.charAt(rand.nextInt(9)) + "");
        }

        return flag.toString();
    }

    public static  linkedList vaildator(T t, Class[] validClass) {
        linkedList errorsMessageList = new linkedList();
        Set> validateSet = Validation.buildDefaultValidatorFactory().getValidator().validate(t, validClass);
        if (!validateSet.isEmpty()) {
            Iterator var4 = validateSet.iterator();

            while(var4.hasNext()) {
                ConstraintViolation cons = (ConstraintViolation)var4.next();
                errorsMessageList.add(new FieldError("form", cons.getPropertyPath().toString(), cons.getMessageTemplate()));
            }
        }

        return errorsMessageList;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5609665.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存