首页   >   代码编程

分享几个常用的Java工具类

在编码过程中,会碰到很多相似的功能,基本上都是有固定的写法,就是传入的参数不一样,所以一般都会抽出一些公用代码来处理,今天来分享几个平时使用的工具类。

MD5工具类:

package com.wolffy.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * MD5加密工具类
 * Created by SongFei on 2016/12/24.
 */
@Slf4j
public class MD5Util {

    /**
     * MD5加密
     *
     * @param str 原文
     * @return 密文
     */
    public static String encrypt(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");

            byte[] bytes = md5.digest(str.getBytes());
            StringBuilder buffer = new StringBuilder();

            for (byte aByte : bytes) {
                // 这句是重点,进制转换时的位补
                int temp = ((int) aByte) & 0xff;
                if (temp < 16) buffer.append("0");
                buffer.append(Integer.toHexString(temp));
            }

            return buffer.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("加密失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(encrypt(encrypt("11111")));
        System.out.println(encrypt(encrypt("11111")));
        System.out.println(encrypt("11111"));
    }

}

AES对称加密工具类:

package com.wolffy.util;

import com.wolffy.core.common.Constants;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * AES对称加密工具
 * <p>
 * 加密和解密均采用同一把秘密钥匙,而且通信双方都必须获得这把钥匙,并保持钥匙的秘密。
 * <p>
 * Created by SongFei on 2016/12/24.
 */
@Slf4j
public class AESUtil {

    private static Cipher cipher;

    private static final String KEY_ALGORTHM = "AES";

    static {
        try {
            cipher = Cipher.getInstance(KEY_ALGORTHM);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            log.error("初始化Cipher失败:{}", ExceptionUtils.getStackTrace(e));
        }
    }

    /**
     * BASE64解密(将字符串转换成byte数组)
     *
     * @param key 字符串
     * @return byte数组
     * @throws IOException IO异常
     */
    private static byte[] decryptBASE64(String key) throws IOException {
        return (new BASE64Decoder()).decodeBuffer(key);
    }

    /**
     * BASE64加密(将byte数组转换成字符串)
     *
     * @param key byte数组
     * @return 字符串
     * @throws IOException IO异常
     */
    private static String encryptBASE64(byte[] key) throws IOException {
        return (new BASE64Encoder()).encodeBuffer(key).trim();
    }

    /**
     * 加密
     *
     * @param content  需要加密的内容
     * @param password 加密密码
     * @return 密文
     */
    public static String encrypt(String content, String password) {
        if (StringUtils.isBlank(content)) {
            return null;
        }
        try {
            SecretKeySpec key = getSecretKeySpec(password);
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            return encryptBASE64(cipher.doFinal(byteContent));
        } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | IOException e) {
            log.error("加密失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content  待解密内容
     * @param password 解密密钥
     * @return 明文
     */
    public static String decrypt(String content, String password) {
        if (StringUtils.isBlank(content)) {
            return null;
        }
        try {
            SecretKeySpec key = getSecretKeySpec(password);
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            return new String(cipher.doFinal(decryptBASE64(content)));
        } catch (IOException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            log.error("解密失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    private static SecretKeySpec getSecretKeySpec(String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORTHM);
            // kgen.init(128, new SecureRandom(password.getBytes()));
            // 上面注释掉的这一句,在linux系统里面会报错,详情可参考 http://www.iteye.com/problems/35327
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            return new SecretKeySpec(enCodeFormat, KEY_ALGORTHM);
        } catch (NoSuchAlgorithmException e) {
            log.error("解析密钥失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public static void main(String[] args) {
        //long startTime = System.currentTimeMillis();
        String miwen = encrypt("ssssssssssssssssssss", Constants.CIPHER_KEY);
        //long endTime = System.currentTimeMillis();
        //System.out.println((endTime - startTime) / 1000f);
        System.out.println(miwen);
        System.out.println(decrypt(miwen, Constants.CIPHER_KEY));
    }

}

RSA非对称加密工具类:

package com.wolffy.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * RSA非对称加密工具,加密钥匙(公钥)和解密钥匙(私钥)不同
 * Created by SongFei on 2016/12/24.
 */
@Slf4j
public class RSAUtil {

    private static Cipher cipher;

    private static final String KEY_ALGORTHM = "RSA";

    static {
        try {
            cipher = Cipher.getInstance(KEY_ALGORTHM);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            log.error("初始化Cipher失败:{}", ExceptionUtils.getStackTrace(e));
        }
    }

    /**
     * 生成密钥对
     *
     * @param filePath 生成密钥的路径
     * @param save     是否生成本地keystore文件
     * @param length   密文长度,过长会影响计算速度(最少512,最大16384)
     * @return 公钥和私钥键值对
     */
    public static Map<String, String> generateKeyPair(String filePath, boolean save, int length) {
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORTHM);
            // 密钥位数
            keyPairGen.initialize(length);
            // 密钥对
            KeyPair keyPair = keyPairGen.generateKeyPair();
            // 公钥
            PublicKey publicKey = keyPair.getPublic();
            // 私钥
            PrivateKey privateKey = keyPair.getPrivate();
            // 得到公钥字符串
            String publicKeyString = getKeyString(publicKey);
            // 得到私钥字符串
            String privateKeyString = getKeyString(privateKey);
            // 将生成的密钥对返回
            Map<String, String> keyMap = new HashMap<>();
            keyMap.put("publicKey", publicKeyString);
            keyMap.put("privateKey", privateKeyString);
            if (!save) {
                return keyMap;
            }
            // 将密钥对写入到文件
            FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
            FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
            BufferedWriter pubbw = new BufferedWriter(pubfw);
            BufferedWriter pribw = new BufferedWriter(prifw);
            pubbw.write(publicKeyString);
            pribw.write(privateKeyString);
            pubbw.flush();
            pubbw.close();
            pubfw.close();
            pribw.flush();
            pribw.close();
            prifw.close();
        } catch (NoSuchAlgorithmException | IOException e) {
            log.error("生成密钥对失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * 得到公钥
     *
     * @param key 密钥字符串(经过base64编码)
     * @return PublicKey
     */
    private static PublicKey getPublicKey(String key) {
        try {
            byte[] keyBytes = (new BASE64Decoder()).decodeBuffer(key);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
            return keyFactory.generatePublic(keySpec);
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            log.error("获取公钥失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * 得到私钥
     *
     * @param key 密钥字符串(经过base64编码)
     * @return PrivateKey
     */
    private static PrivateKey getPrivateKey(String key) {
        try {
            byte[] keyBytes = (new BASE64Decoder()).decodeBuffer(key);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
            return keyFactory.generatePrivate(keySpec);
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            log.error("获取私钥失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * 得到密钥字符串(经过base64编码)
     *
     * @return 密钥字符
     */
    private static String getKeyString(Key key) {
        byte[] keyBytes = key.getEncoded();
        return (new BASE64Encoder()).encode(keyBytes);
    }

    /**
     * 使用公钥对明文进行加密,返回BASE64编码的字符串
     *
     * @param publicKey 公钥
     * @param plainText 明文
     * @return 密文
     */
    public static String encrypt(PublicKey publicKey, String plainText) {
        try {
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] enBytes = cipher.doFinal(plainText.getBytes());
            return (new BASE64Encoder()).encode(enBytes);
        } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException e) {
            log.error("公钥加密失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * 使用私钥对密文进行解密
     *
     * @param privateKey 私钥
     * @param enStr      密文
     * @return 明文
     */
    public static String decrypt(PrivateKey privateKey, String enStr) {
        try {
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));
            return new String(deBytes);
        } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | IOException e) {
            log.error("私钥解密失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * 使用keystore对明文进行加密
     *
     * @param publicKeystorePath 公钥文件路径
     * @param plainText          明文
     * @return 密文
     */
    public static String encrypt(String publicKeystorePath, String plainText) {
        try {
            String publicKeyString = getKeyStore(publicKeystorePath);
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKeyString));
            byte[] enBytes = cipher.doFinal(plainText.getBytes());
            return (new BASE64Encoder()).encode(enBytes);
        } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            log.error("公钥加密失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * 使用keystore对密文进行解密
     *
     * @param privateKeystorePath 私钥路径
     * @param enStr               密文
     * @return 明文
     */
    public static String decrypt(String privateKeystorePath, String enStr) {
        try {
            String privateKeyString = getKeyStore(privateKeystorePath);
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyString));
            byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));
            return new String(deBytes);
        } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | IOException e) {
            log.error("私钥解密失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * 读取密钥文件,转换成密钥字符串
     *
     * @param keystorePath 密钥文件路径
     * @return 密钥字符
     */
    private static String getKeyStore(String keystorePath) {
        try {
            FileReader fr = new FileReader(keystorePath);
            BufferedReader br = new BufferedReader(fr);
            String publicKeyString = "";
            String str;
            while ((str = br.readLine()) != null) {
                publicKeyString += str;
            }
            br.close();
            fr.close();
            return publicKeyString;
        } catch (IOException e) {
            log.error("读取密钥文件失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            Map<String, String> map = generateKeyPair("D://", false, 512);
            String miwen = encrypt(getPublicKey(map.get("publicKey")), "大风起兮云飞扬");
            System.out.println(miwen);
            System.out.println(decrypt(getPrivateKey(map.get("privateKey")), miwen));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Cookie工具类:

package com.wolffy.util;

import com.wolffy.core.common.Constants;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie工具类
 * Created by SongFei on 2016/12/24.
 */
public class CookieUtil {

    /**
     * 设置cookie信息(键值形式存储)
     *
     * @param key    键
     * @param value  值
     * @param expire 存活时间(单位是秒)
     */
    public static void set(HttpServletResponse response, String key, String value, Integer expire) {
        Cookie cookie = new Cookie(key, AESUtil.encrypt(value, Constants.CIPHER_KEY));//全部进行AES加密
        //Cookie cookie = new Cookie(key, URLEncoder.encode(value, "utf-8"));//中文需要进行转码
        //跨域使用,cookie子域共享
        //String host = request.getServerName();
        //cookie.setDomain(host);
        cookie.setPath("/");
        cookie.setMaxAge(expire);
        response.addCookie(cookie);
    }

    /**
     * 获取cookie中的信息
     *
     * @param key 键(cookie中存放的信息是键值的形式)
     * @return 字符串(cookie存放的信息都是字符串)
     */
    public static String get(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (null == cookies || cookies.length < 1) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())) {
                return AESUtil.decrypt(cookie.getValue().trim(), Constants.CIPHER_KEY);
            }
        }
        return null;
    }

    /**
     * 清除cookie,只需要将maxage设置为0即可
     *
     * @param key 要清除的值
     */
    public static void del(HttpServletResponse response, String key) {
        Cookie cookie = new Cookie(key, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

}

Session工具类:

package com.wolffy.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Session工具类
 * Created by SongFei on 2016/12/24.
 */
public class SessionUtil {

    /**
     * 获取session
     *
     * @param request 请求
     * @return HttpSession
     */
    public static HttpSession getSession(HttpServletRequest request) {
        if (null == request) return null;
        return request.getSession();
    }

    public static String getSessionId(HttpServletRequest request) {
        HttpSession session = getSession(request);
        return session == null ? null : session.getId();
    }

    /**
     * 将内容放入session中
     *
     * @param key   键
     * @param value 值
     */
    public static void set(HttpServletRequest request, String key, Object value) {
        if (null == getSession(request) || null == value) {
            return;
        }
        getSession(request).setAttribute(key, value);
    }

    /**
     * 获取session中的内容
     *
     * @param key 键
     * @return key对应的值
     */
    public static Object get(HttpServletRequest request, String key) {
        if (null == getSession(request) || StringUtils.isBlank(key)) {
            return null;
        }
        return getSession(request).getAttribute(key);
    }

    /**
     * 移除session中的内容
     *
     * @param key 键
     */
    public static void del(HttpServletRequest request, String key) {
        if (null == getSession(request) || StringUtils.isBlank(key)) {
            return;
        }
        getSession(request).removeAttribute(key);
    }

}

日期格式化工具类:

package com.wolffy.util;

import com.wolffy.core.common.Constants;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Calendar;
import java.util.Date;

/**
 * 时间工具类
 * Created by SongFei on 2016/12/24.
 */
public class DateUtil {

    // public static final long SENCOND = 60;

    private static final String MINUTE_STR = "分钟前";

    // public static final long MINUTES = 60;

    private static final String HOUSR_STR = "小时前";

    // public static final long HOUSRS = 24;

    private static final String DAY_STR = "天前";

    private static final String YEAR_STR = "年前";

    /**
     * 获取多长时间之前(例:5分钟前)
     *
     * @param date 时间
     * @return 时间字符串
     */
    public static String getTimeStr(Date date) {
        Date now = new Date();

        long days = (now.getTime() - date.getTime()) / 3600000 / 24;

        long hours = (now.getTime() - date.getTime()) / 3600000;

        long minutes = (now.getTime() - date.getTime()) / 60000;

        if (days > 365) {
            return days + YEAR_STR;
        } else if (days > 0) {
            return days + DAY_STR;
        } else if (hours < 24 && hours > 0) {
            return hours + HOUSR_STR;
        } else if (minutes < 60 && minutes > 0) {
            return minutes + MINUTE_STR;
        } else {
            return 1 + MINUTE_STR;
        }
    }

    /**
     * 格式化日期,返回yyyy-MM-dd
     *
     * @param date 日期
     * @return 格式化字符
     */
    public static String formatDate(Date date) {
        return date == null ? "" : DateFormatUtils.format(date, Constants.DATE_PATTERN);
    }

    /**
     * 格式化日期,返回yyyy/MM/dd
     *
     * @param date 日期
     * @return 格式化字符
     */
    public static String formatDate2(Date date) {
        return date == null ? "" : DateFormatUtils.format(date, Constants.DATE_PATTERN2);
    }

    /**
     * 格式化日期,返回yyyyMMdd
     *
     * @param date 日期
     * @return 格式化字符
     */
    public static String formatDate3(Date date) {
        return date == null ? "" : DateFormatUtils.format(date, Constants.DATE_PATTERN3);
    }

    /**
     * 格式化时间,返回yyyy-MM-dd HH:mm:ss
     *
     * @param date 日期
     * @return 格式化字符
     */
    public static String formatTime(Date date) {
        return date == null ? "" : DateFormatUtils.format(date, Constants.TIME_PATTERN);
    }

    /**
     * 获取日期所在的本周第一天
     *
     * @param date 日期
     * @param end  一天的最后时刻,23:59:59,默认是00:00:00
     * @return 本周第一天
     */
    public static Date weekFirstDay(Date date, boolean end) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        startOrEnd(calendar, end);
        int day = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (day == 1) {
            return calendar.getTime();
        }
        if (day == 0) {
            day = 7;// 老外将周日算作1,所以依次递减,周日就是0
        }
        calendar.add(Calendar.DATE, -(day - 1));
        return calendar.getTime();
    }

    /**
     * 获取日期所在的本周最后一天
     *
     * @param date 日期
     * @param end  一天的最后时刻,23:59:59,默认是00:00:00
     * @return 本周最后一天
     */
    public static Date weekLastDay(Date date, boolean end) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        startOrEnd(calendar, end);
        int day = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (day == 0) {
            return calendar.getTime();// 老外将周日算作1,所以依次递减,周日就是0
        }
        calendar.add(Calendar.DATE, 7 - day);
        return calendar.getTime();
    }

    /**
     * 设置时分秒,根据参数控制是 00:00:00 还是 23:59:59
     *
     * @param calendar 日期
     * @param end      是否结尾日期,true就是23:59:59,false是00:00:00
     */
    private static void startOrEnd(Calendar calendar, boolean end) {
        if (end) {
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
        } else {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
        }
    }

    public static void main(String[] args) {
        //Calendar calendar = Calendar.getInstance();
        //System.out.println(calendar.getTime());
        //calendar.add(Calendar.DATE, 1);
        //System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
        //System.out.println(calendar.get(Calendar.DAY_OF_WEEK) - 1);
        //calendar.add(Calendar.DATE, -6);
        //System.out.println(calendar.getTime());
        System.out.println(weekFirstDay(new Date(), false));
        System.out.println(weekLastDay(new Date(), true));
    }

}

序列化工具类:

package com.wolffy.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * 序列化工具类
 * Created by SongFei on 2016/12/24.
 */
@Slf4j
public class SerializeUtil {

    /**
     * 序列化(将对象转换成byte数组)
     *
     * @param object 对象
     * @return byte数组
     */
    public static byte[] serialize(Object object) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("序列化失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * 反序列化(将byte数组转换成对象)
     *
     * @param bytes 字节数组
     * @return obj对象
     */
    public static Object unserialize(byte[] bytes) {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            log.error("反序列化失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

}

获取IP工具类:

package com.wolffy.util;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取用户IP工具类
 * Created by SongFei on 2017/7/5.
 */
public class IpUtil {

    private static final String[] IP_HEADERS_TO_TRY = {"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP", "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR", "X-Real-IP"};

    /**
     * 浏览器固定请求头字符
     */
    private static final String USER_AGENT = "User-Agent";

    /**
     * 获取远程用户端IP
     *
     * @param request 请求
     * @return 用户IP地址
     */
    public static String getClientIP(HttpServletRequest request) {
        for (String header : IP_HEADERS_TO_TRY) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }
        return request.getRemoteAddr();
    }

    /**
     * 获取远程用户浏览器类型
     *
     * @param request 请求
     * @return 浏览器类型
     */
    public static String getUserAgent(HttpServletRequest request) {
        if (null == request) {
            return null;
        }
        return request.getHeader(USER_AGENT);
    }

}

计算分页工具类:

package com.wolffy.util;

import com.wolffy.core.common.Constants;

/**
 * 分页工具类
 * Created by SongFei on 2017/3/24.
 */
public class PageUtil {

    /**
     * 计算总分页数,默认分页数量
     *
     * @param totalCount 总数量
     * @param pageSize   页码
     * @return 总页数
     */
    public static Integer totalPage(Integer totalCount, Integer pageSize) {
        if (totalCount == null || totalCount <= 0 || pageSize == null || pageSize <= 0) {
            return 0;
        }
        // 小于一页,直接返回
        if (totalCount <= Constants.DEFAULT_PAGE_SIZE) {
            return 1;
        }
        return totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
    }

}

spring获取bean工具类:

package com.wolffy.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Spring获取bean的工具类,用于非spring托管的地方
 * Created by SongFei on 2016/12/25.
 */
public class ProxyUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ProxyUtil.applicationContext = applicationContext;
    }

    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) throws BeansException {
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) throws BeansException {
        if (StringUtils.isBlank(name)) return getBean(clazz);
        if (clazz == null) return getBean(name);
        return applicationContext.getBean(name, clazz);
    }

}

解析URL工具类:

package com.wolffy.util;

import java.net.MalformedURLException;
import java.net.URL;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * 解析java.net.URL
 * Created by wolffy on 2019/4/10
 */
@Slf4j
public class UrlUtil {

    public static String getDomain(String url) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            URL url1 = new URL(url);
            String domain = url1.getProtocol() + "://" + url1.getHost();
            log.info("域名: " + domain);
            return domain;
        } catch (MalformedURLException e) {
            log.error("解析[{}]域名失败: {}", url, ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public static String getProtocol(String url) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            return new URL(url).getProtocol();
        } catch (MalformedURLException e) {
            log.error("获取protocol失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public static String getHost(String url) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            return new URL(url).getHost();
        } catch (MalformedURLException e) {
            log.error("获取host失败:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

}

QQ群: 686430774  /  718410762

站长Q: 1347384268

如果文章有帮到你,可以考虑请博主喝杯咖啡!

分享到:

欢迎分享本文,转载请注明出处!

作者:不忘初心

发布时间:2019-04-11

永久地址:https://www.jiweichengzhu.com/article/bf51fd1946804615abfc65fd17e905a5

评论