项目常用工具类(结合上篇springboot结合iview-vue实现登录demo(一))

常用的工具类

1.字符串工具类

package com.cscrb.utils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class StringUtils {

    public final static String REG_DIGIT = "[0-9]*";
    public final static String REG_CHAR = "[a-zA-Z]*";
    public final static String EMPTY = "";

    /**
     * 判断是否为空
     */
    public static boolean isEmpty(Object... obj) {
        if (obj == null || "".equals(obj))
            return true;
        for (Object object : obj) {
            if (object == null)
                return true;
            if (object.toString().trim().length() == 0)
                return true;
        }

        return false;
    }

    public static boolean isBlankEmpty(Object obj) {
        if (obj == null || "".equals(obj) || "".equals(obj.toString().trim()) || "null".equalsIgnoreCase(obj.toString()))
            return true;

        return false;
    }

    public static Object nullToSpace(Object o) {
        if (null == o) {
            return "";
        }
        return o;
    }

    public static Integer strToInt(Object obj) {
        if (null == obj || "".equals(obj)) {
            return null;
        }
        return Integer.parseInt(obj.toString());
    }

    public static String objNotNull(Object obj) {
        if (null == obj || "".equals(obj)) {
            return null;
        }
        return obj.toString();
    }

    public static Long strToLong(Object obj) {
        if (null == obj || "".equals(obj)) {
            return null;
        }
        return Long.parseLong(obj.toString());
    }

    public static Date strToDate(Object obj) {
        if (null == obj || "".equals(obj)) {
            return null;
        }
        return new Date(Long.parseLong(obj.toString()));
    }

    /**
     * 是否空,或者为空串,或者为"null"
     */
    public static boolean isBlankEmpty(Object... objs) {
        if (objs == null || objs.length == 0)
            return true;
        for (Object obj : objs) {
            if (isBlankEmpty(obj)) {
                return true;
            }
        }

        return false;
    }

    public static boolean isNotBlank(String pattern) {
        return !isBlankEmpty(pattern);
    }

    public static boolean isBlank(String pattern) {
        return isBlankEmpty(pattern);
    }

    public static String formatCountNames(String nameList) {
        String[] names = nameList.split(",");

        Map<String, Integer> nameCount = new HashMap<String, Integer>();
        for (String name : names) {
            if (StringUtils.isEmpty(name)) continue;
            if (nameCount.containsKey(name)) {
                Integer count = nameCount.get(name) + 1;
                nameCount.put(name, count);
            } else {
                nameCount.put(name, 1);
            }
        }

        StringBuilder newNames = new StringBuilder();
        for (String key : nameCount.keySet()) {
            if (StringUtils.isEmpty(key)) continue;
            Integer count = nameCount.get(key);
            String splitChar = newNames.length() > 0 ? "," : "";
            newNames.append(splitChar).append(key).append("x").append(count);
        }

        return newNames.toString();
    }


    public static boolean isDigit(String str) {
        return isNumeric(str);
    }

    public static boolean isChar(String str) {
        return str.matches(REG_CHAR);
    }

    public static Boolean isNotEmpty(Object... obj) {
        Boolean r = StringUtils.isEmpty(obj);
        return !r;
    }

    public static boolean isNumeric(String str) {
        if (isBlankEmpty(str)) return false;
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }

        return true;
    }

    /**
     * string 中的 str 在倒数 num 中的位置
     */
    public static int stringLastlndex(String string, String str, int num) {
        int indexOf = string.lastIndexOf(str);
        if (num > 1) {
            return stringLastlndex(string.substring(0, indexOf), str, num - 1);
        } else {
            return indexOf;
        }
    }


    public static String getValue(Object val) {
        return val == null ? "" : val.toString();
    }
    
}

2.封装的结果集工具类

package com.cscrb.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * @Classname Response
 * @Description 封装返回结果集
 * @Date 2020/3/6 16:29
 */
public class Response extends HashMap<String,Object> {
    private final static String CODE = "code";
    private final static String DATA = "data";
    private final static String TOTAL = "total";
    private final static String MESSAGE = "message";


    private Logger logger = LoggerFactory.getLogger(Response.class);

    private Response() {
        this.put(CODE, ErrorEnum.SUCCESS.getCode());
        this.put(MESSAGE, ErrorEnum.SUCCESS.getMessage());
    }

    public static Response newResponse() {
        return new Response();
    }

    public static Response set(Integer total, Object rows) {
        Response response = new Response();
        response.setTotal(total);
        response.ok(rows);
        return response;
    }

    public static Response set(Object rows) {
        Response response = new Response();
        response.ok(rows);

        return response;
    }

    public static Response set(String key, Object value) {
        Response response = Response.newResponse();
        response.put(key, value);
        return response;
    }

    public Response setData(Object data){
        this.put(DATA, data);
        return this;
    }

    public Response put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    /**
     * 获得错误消息
     */
    public String getMessage() {
        Object msg = this.get(MESSAGE);
        return msg != null ? msg.toString() : null;
    }

    public Response moveTo(String fromKey, String toKey) {
        Object val = this.get(fromKey);
        this.put(toKey, val);
        this.remove(fromKey);
        return this;
    }

    public Boolean isOK() {
        return this.getCode() == ErrorEnum.SUCCESS.getCode();
    }

    public Boolean isFail() {
        return !isOK();
    }

    public Response ok(Object data) {
        super.put(DATA, data);
        return this;
    }

    public Response ok(String key, Object val) {
        super.put(key, val);
        return this;
    }

    public Response setResults(Integer count, Object data) {
        this.setTotal(count);
        this.ok(data);
        return this;
    }

    private Response setCode(int code) {
        this.put(CODE, code);
        return this;
    }

    /**
     * 设置返回码与返回信息
     * 强列建议在ErrorEnum 中定义错误, 再调用setError()方法
     * @param code
     * @param message
     * @return
     */
    public Response setCodeAndMessage(int code, String message) {
        this.put(CODE, code);
        this.put(MESSAGE, message);
        return this;
    }

    public Response setMessage(String message) {
        this.put(MESSAGE, message);
        return this;
    }

    public int getCode() {
        return Integer.parseInt(this.get(CODE).toString());
    }

    public Response setTotal(Integer total) {
        this.put(TOTAL, total);
        return this;
    }

    public Response OK() {
        this.setCode(ErrorEnum.SUCCESS.getCode());
        this.put(MESSAGE, "ok");
        return this;
    }

    /**
     * 设置错误类型
     * 传入ErrorEnum 枚举
     */
    public Response setError(ErrorEnum errorEnum){
        this.setCode(errorEnum.getCode());
        this.setMessage(errorEnum.getMessage());
        return this;
    }
}

3.错误枚举类

package com.cscrb.utils;

/**
 * @Classname ErrorEnum
 * @Description 返回结果值枚举类
 * @Date 2020/3/6 16:23
 */
public enum ErrorEnum {
    SUCCESS(200, "ok"),
    account_password_err(10012,"用户名或密码错误!"),
    account_password_null(10013,"用户名或密码为空!"),
    
    ;
    private String message;

    private int code;

    ErrorEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public int getCode() {
        return code;
    }
}

4.日志工具类

package com.cscrb.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Classname LogUtils
 * @Description 日志工具类
 * @Date 2020/3/6 16:55
 */
public class LogUtils {
    /**
     * 获得Logger
     * @param clazz 日志发出的类
     * @return Logger
     */
    public static Logger get(Class<?> clazz) {
        return LoggerFactory.getLogger(clazz);
    }

    public static Logger get(String name) {
        return LoggerFactory.getLogger(name);
    }

    public static Logger get() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        return LoggerFactory.getLogger(stackTrace[2].getClassName());
    }

    public static void trace(Logger log, String format, Object... arguments) {
        log.trace(format, arguments);
    }

    public static void debug(Logger log, String format, Object... arguments) {
        log.debug(format, arguments);
    }

    public static void info(Logger log, String format, Object... arguments) {
        log.info(format, arguments);
    }

    public static void warn(Logger log, String format, Object... arguments) {
        log.warn(format, arguments);
    }

    public static void warn(Logger log, Throwable e, String format, Object... arguments) {
        log.warn(format(format, arguments), e);
    }

    public static void error(Logger log, String format, Object... arguments) {
        log.error(format, arguments);
    }

    public static void error(Logger log, Throwable e, String format, Object... arguments) {
        log.error(format(format, arguments), e);
    }
    
    private static String format(String template, Object... values) {
        return String.format(template.replace("{}", "%s"), values);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值