deveop工具类

目录

引言

一 常量类

二 枚举类

1 DataEnum

2 CodeEnum

三 工具类

1 Date

2 String

3 redis

4 redirectUtil

5 Http请求工具

6  cookie

7 jwt

8 RSA

四 实体类

五返回结果集类

1 第一种

六 配置类

1aop切面类

2 filter过滤类

3  拦截器类

4 监听器类



引言

只为记录写法,对于新项目,便于快速搭建使用工具

一 常量类

public class LanguageConstant {
    public static final String CN = "cn";
    public static final String EN = "en";
}

二 枚举类

1 DataEnum

public enum DateEnum {

    DAY(1, "day"),
    WEEK(2, "week"),
    MONTH(3, "month");

    private int key;

    private String value;

    DateEnum(int key, String value) {
        this.key = key;
        this.value = value;
    }

    public int getKey() {
        return key;
    }

    public String getValue() {
        return value;
    }

}

2 CodeEnum

public enum CodeEnum implements BaseGetCodeEnum<Integer> {
    /**
     * 系统错误码
     */
    SUCCESS_CODE(0, "成功"),
    FALSE_CODE(1, "失败"),
    NOT_LOGIN(1000, "用户未登录"),
    NO_PRIVILEGE(1001, "用户无权限"),
    SELECT_NULL(2,"查询无果"),
    DESC_TOO_LONG(3,"描述过长"),
    NAME_TOO_LONG(4,"名称不宜过长")

    ;


    private int code;
    private String describe;

    CodeEnum(int code, String describe) {
        this.code = code;
        this.describe = describe;
    }
    public int getCode() {
        return code;
    }
    @Override
    public Integer getEnumId() {
        return code;
    }

    public String getDescribe() {
        return describe;
    }

}

三 工具类

1 Date

所需依赖:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>
package org.tool.demo.util;


import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期工具类
 *
 */
public class DateFormatUtil {

    /**
     * 获取日期(Date类型)
     * YDHM
     *
     * @param format
     * @return format || yyyy-MM-dd
     */
    public static Date getDate(String format) {
        if (StringUtils.isBlank(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat f = new SimpleDateFormat(format);
        try {
            return f.parse(f.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取日期(Date类型)
     *
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static Date getDateYMDHMS() {
        return getDate("yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 获取日期(Date类型)
     *
     * @return yyyy-MM-dd
     */
    public static Date getDateYMD() {
        return getDate("yyyy-MM-dd");
    }

    /**
     * 获取日期(Date类型)
     *
     * @return yyyy-MM
     */
    public static Date getDateYM() {
        return getDate("yyyy-MM");
    }

    /**
     * 获取日期(Date类型)
     *
     * @return yyyy
     */
    public static Date getDateY() {
        return getDate("yyyy");
    }

    /**
     * 获取日期(String类型)
     *
     * @return format || yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate(String format) {
        if (StringUtils.isBlank(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat f = new SimpleDateFormat(format);
        try {
            return f.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取日期(String类型)
     *
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDateYMDHMS() {
        return getStringDate(null);
    }

    /**
     * 获取日期(String类型)
     *
     * @return yyyy-MM-dd
     */
    public static String getStringDateYMD() {
        return getStringDate("yyyy-MM-dd");
    }

    /**
     * 获取日期(String类型)
     *
     * @return yyyy-MM
     */
    public static String getStringDateYM() {
        return getStringDate("yyyy-MM");
    }

    /**
     * 将Date型转为String型
     *
     * @param date
     * @param format
     * @return format || null
     */
    public static String formatDate(Date date, String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * 将Date型转为String型
     *
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String formatDateYMDHMS(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 将Date型转为String型
     *
     * @param date
     * @return yyyy-MM-dd HH:mm
     */
    public static String formatDateYMDHM(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm");
    }

    /**
     * 将Date型转为String型
     *
     * @param date
     * @return yyyy-MM-dd
     */
    public static String formatDateYMD(Date date) {
        return formatDate(date, "yyyy-MM-dd");
    }

    /**
     * 将Date型转为String型
     *
     * @param date
     * @return yyyy-MM
     */
    public static String formatDateYM(Date date) {
        return formatDate(date, "yyyy-MM");
    }

    /**
     * 将Date型转为String型
     *
     * @param date
     * @return yyyy
     */
    public static String formatDateY(Date date) {
        return formatDate(date, "yyyy");
    }

    /**
     * 将Date型转为String型
     *
     * @param date
     * @return yyyy
     */
    public static String formatDateToStringYM(Date date) {
        return formatDate(date, "yyyy年MM月");
    }


    /**
     * 当前日期减去天数
     *
     * @param days 天数 为正数时当前日期减去天数;为负数时当前日期加上天数
     * @return yyyy-MM-dd
     */
    public static String currentDateMinusDays(int days) {
        LocalDateTime dateTime = LocalDateTime.now().minusDays(days);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String localTime = df.format(dateTime);
        return localTime;
    }


    /**
     * 将String型转为String型
     *
     * @param date
     * @param format
     * @return format || null
     */
    public static String formatStringDate(String date, String format) {
        if (StringUtils.isNotBlank(date)) {
            try {
                String dateformat = format.replace("年", "-").replace("月", "-").replace("日", "");
                SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
                Date d = sdf.parse(date);
                sdf = new SimpleDateFormat(format);
                return sdf.format(d);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 将String型转为String型
     *
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String formatStringDateYMDHMS(String date) {
        return formatStringDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 将String型转为String型
     *
     * @param date
     * @return yyyy-MM-dd HH:mm
     */
    public static String formatStringDateYMDHM(String date) {
        return formatStringDate(date, "yyyy-MM-dd HH:mm");
    }

    /**
     * 将String型转为String型
     *
     * @param date
     * @return yyyy-MM-dd
     */
    public static String formatStringDateYMD(String date) {
        return formatStringDate(date, "yyyy-MM-dd");
    }

    /**
     * 将String型转为String型
     *
     * @param date
     * @return yyyy-MM
     */
    public static String formatStringDateYM(String date) {
        return formatStringDate(date, "yyyy-MM");
    }

    /**
     * 将String型转为String型
     *
     * @param date
     * @return yyyy
     */
    public static String formatStringDateY(String date) {
        return formatStringDate(date, "yyyy");
    }

    /**
     * 将String型转为Date型
     *
     * @param value
     * @param format
     * @return format || yyyy-MM-dd
     */
    public static Date convertDate(String value, String format) {
        if (StringUtils.isBlank(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        if (StringUtils.isNotBlank(value)) {
            try {
                return sdf.parse(value);
            } catch (ParseException e) {
                //log.error("time convertDate error:{}", e);
            }
        }
        return null;
    }

    /**
     * 将String型转为Date型
     *
     * @param value
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static Date convertDateYMDHMS(String value) {
        return convertDate(value, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 将String型转为Date型
     *
     * @param value
     * @return yyyy-MM-dd HH:mm
     */
    public static Date convertDateYMDHM(String value) {
        return convertDate(value, "yyyy-MM-dd HH:mm");
    }

    /**
     * 将String型转为Date型
     *
     * @param value
     * @return yyyy-MM-dd
     */
    public static Date formatDateYMD(String value) {
        return convertDate(value, "yyyy-MM-dd");
    }

    /**
     * 把String类型时间戳转换为String类型的年月日"yyyy-MM-dd"
     *
     * @param date
     * @return
     */
    public static String formatStringToYMD(String date) {
        String format = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(date)));
    }

    /**
     * 把Long类型时间戳转换为String类型的月日 时分"MM-dd HH:mm"
     *
     * @param date
     * @return
     */
    public static String formatStringToMDHM(Long date) {
        String format = "MM-dd HH:mm";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(date)));
    }

    /**
     * 把Long类型时间戳转换为String类型的月日 时分"MM-dd HH:mm"
     *
     * @param date
     * @return
     */
    public static String formatStringToYMD(Long date) {
        String format = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(date)));
    }

    /**
     * 把Long类型时间戳转换为String类型的月日 时分"MM-dd HH:mm"
     *
     * @param date
     * @return
     */
    public static String formatStringToYMDHM(Long date) {
        String format = "yyyy-MM-dd HH:mm";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(date)));
    }


    /**
     * 将String型转为Date型
     *
     * @param value
     * @return yyyy-MM-dd
     */
    public static Date convertDateYMD(String value) {
        return convertDate(value, "yyyy-MM-dd");
    }


    /**
     * 将String型转为Date型
     *
     * @param value
     * @return yyyy-MM
     */
    public static Date convertDateYM(String value) {
        return convertDate(value, "yyyy-MM");
    }


    /**
     * 将String型转为Date型
     *
     * @param value
     * @return yyyy
     */
    public static Date convertDateY(String value) {
        return convertDate(value, "yyyy");
    }

    /**
     * 将Date型转为Date型
     *
     * @param date
     * @param format
     * @return format || yyyy-MM-dd
     */
    public static Date convertDateToDate(Date date, String format) {
        if (StringUtils.isBlank(format)) {
            format = "yyyy-MM-dd";
        }
        if (date != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                return sdf.parse(sdf.format(date));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 将Date型转为Date型
     *
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static Date convertDateToDateYMDHMS(Date date) {
        return convertDateToDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 将Date型转为Date型
     *
     * @param date
     * @return yyyy-MM-dd
     */
    public static Date convertDateToDateYMD(Date date) {
        return convertDateToDate(date, "yyyy-MM-dd");
    }

    /**
     * 将Date型转为Date型
     *
     * @param date
     * @return yyyy-MM
     */
    public static Date convertDateToDateYM(Date date) {
        return convertDateToDate(date, "yyyy-MM");
    }

    /**
     * 将Date型转为Date型
     *
     * @param date
     * @return yyyy
     */
    public static Date convertDateToDateY(Date date) {
        return convertDateToDate(date, "yyyy");
    }

    /**
     * 获取两个日期相差的天数
     *
     * @param beginDate
     * @param endDate
     */
    public static long getDifferDay(Date beginDate, Date endDate) {
        long day = (beginDate.getTime() - endDate.getTime()) / (24 * 60 * 60 * 1000) > 0
                ? (beginDate.getTime() - endDate.getTime()) / (24 * 60 * 60 * 1000)
                : (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
        return day;
    }

    /**
     * 获取两个日期相差的月份
     *
     * @param beginDate
     * @param endDate
     */
    public static int getMonthSpace(Date beginDate, Date endDate) {
        int result = 0;
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(beginDate);
        c2.setTime(endDate);
        if (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR) > 0) {
            result = 12 * (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR) - 1);
            result += (12 - c1.get(Calendar.MONTH));
            result += (c2.get(Calendar.MONTH) + 1);
        } else {
            result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
        }
        return result;
    }

    /**
     * 获取年份
     *
     * @return String型
     */
    public static String getYear() {
        return getIntYear() + "";
    }

    /**
     * 获取年份
     */
    public static Integer getIntYear() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.YEAR);
    }

    /**
     * 从date型时间中获取年份
     *
     * @param date
     */
    public static String getYear(Date date) {
        if (date != null) {
            return getIntYear() + "";
        }
        return null;
    }

    /**
     * 从date型时间中获取年份
     *
     * @param date
     */
    public static Integer getIntYear(Date date) {
        if (date != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            return cal.get(Calendar.YEAR);
        }
        return null;
    }

    /**
     * 从string型时间中获取年份
     *
     * @param date
     */
    public static Integer getIntYear(String date) {
        if (date != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(convertDateYMD(date));
            return cal.get(Calendar.YEAR);
        }
        return null;
    }

    /**
     * 获取date指定的日期是一个月的第几天
     *
     * @param date
     */
    public static Integer getDayOfMonth(Date date) {
        return getTime(date, Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取当前日期 一天的时刻
     *
     * @param date
     */
    public static Integer getHourOfDay(Date date) {
        return getTime(date, Calendar.HOUR_OF_DAY);
    }

    /**
     * 获取指定日期的月份
     *
     * @param date
     */
    public static Integer getMonth(Date date) {
        return getTime(date, Calendar.MONTH) + 1;
    }

    /**
     * 获取时间类别
     *
     * @param date
     * @param timeType
     */
    public static Integer getTime(Date date, int timeType) {
        int rst = -1;
        if (date != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            rst = calendar.get(timeType);
        }
        return rst;
    }

    /**
     * 减去当前日期小时
     *
     * @param date
     * @param hour 要减去的小时数
     */
    public static Date decreaseDateByHour(Date date, int hour) {
        int dayHour = getHourOfDay(date) - hour;
        return formatDateSetHour(date, dayHour);
    }

    /**
     * 减去当前日期天数
     *
     * @param date
     * @param day  要减去的天数
     */
    public static Date decreaseDateByDay(Date date, int day) {
        int dayOfMonth = getDayOfMonth(date) - day;
        return formatDateSetDay(date, dayOfMonth);
    }

    /**
     * 减去当前日期月数
     *
     * @param date
     * @param month 要减去的月数
     */
    public static Date decreaseDateByMonth(Date date, int month) {
        int gMonth = getMonth(date) - month;
        return formatDateSetMonth(date, gMonth);
    }

    /**
     * 设置日期月份
     *
     * @param date
     * @param month
     */
    public static Date formatDateSetMonth(Date date, int month) {
        if (date != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.MONTH, month - 1);
            return calendar.getTime();
        }
        return null;
    }

    /**
     * 设置日期年份
     *
     * @param date
     * @param year
     */
    public static Date formatDateSetYear(Date date, int year) {
        if (date != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.YEAR, year);
            return calendar.getTime();
        }
        return null;
    }

    /**
     * 设置日期天
     *
     * @param date
     * @param day
     */
    public static Date formatDateSetDay(Date date, int day) {
        if (date != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.DAY_OF_MONTH, day);
            return calendar.getTime();
        }
        return null;
    }

    /**
     * 设置日期小时
     *
     * @param date
     * @param hour
     */
    public static Date formatDateSetHour(Date date, int hour) {
        if (date != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.HOUR_OF_DAY, hour);
            return calendar.getTime();
        }
        return null;
    }

    /**
     * 将一个日期增加(amount为正数)或减少(amount为负数)指定的量
     *
     * @param date   日期
     * @param field  要改变的领域
     * @param amount 数量
     */
    public static Date add(Date date, int field, int amount) {
        if (date != null) {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.add(field, amount);
            return c.getTime();
        }
        return null;
    }

    /**
     * 将一个日期增加n年
     *
     * @param date
     * @param amount 增加的年数
     */
    public static Date addYear(Date date, int amount) {
        return add(date, Calendar.YEAR, amount);
    }

    /**
     * 将一个日期增加n月
     *
     * @param date
     * @param amount 增加的月数
     */
    public static Date addMonth(Date date, int amount) {
        return add(date, Calendar.MONTH, amount);
    }

    /**
     * 将一个日期增加n天
     *
     * @param date
     * @param amount 增加的天数
     */
    public static Date addDay(Date date, int amount) {
        return add(date, Calendar.DATE, amount);
    }

    /**
     * 将一个日期增加n小时
     *
     * @param date   格式:yyyy-MM-dd HH:mm:ss
     * @param amount 增加的小时数
     */
    public static Date addHour(Date date, int amount) {
        return add(date, Calendar.HOUR_OF_DAY, amount);
    }

    /**
     * 将一个日期增加n分钟
     *
     * @param date   格式:yyyy-MM-dd HH:mm:ss
     * @param amount 增加的分钟数
     */
    public static Date addMinute(Date date, int amount) {
        return add(date, Calendar.MINUTE, amount);
    }

    /**
     * 将一个日期增加n秒
     *
     * @param date   格式:yyyy-MM-dd HH:mm:ss
     * @param amount 增加的秒数
     */
    public static Date addSecond(Date date, int amount) {
        return add(date, Calendar.SECOND, amount);
    }

    /**
     * 将一个日期增加n天
     *
     * @param date
     * @param n    增加的天数
     */
    public static String addDay(String date, int n) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.setTime(format.parse(date));
            c.add(Calendar.DATE, n);
            return format.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取一周的周一和周日两天
     */
    public static String[] getMondayAndSunday(String str) {
        String[] result = new String[2];
        Calendar calendar = Calendar.getInstance(); // 创建日历实例,默认当前日期
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 设置日期格式
        try {
            Date date = sDateFormat.parse(str);
            calendar.setTime(date);
            int flag = calendar.get(Calendar.DAY_OF_WEEK); // 获得礼拜几信息
            // 获得当前礼拜
            calendar.add(Calendar.DAY_OF_YEAR, -flag + 2);
            date = calendar.getTime();
            result[0] = sDateFormat.format(date); // 礼拜一
            calendar.add(Calendar.DAY_OF_YEAR, 6);
            date = calendar.getTime();
            result[1] = sDateFormat.format(date); // 礼拜天
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 获取一周的日期
     */
    public String[] getWeeks(String str) {
        String[] result = new String[7];
        Calendar calendar = Calendar.getInstance(); // 创建日历实例,默认当前日期
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 设置日期格式
        try {
            Date date = sDateFormat.parse(str);
            calendar.setTime(date);
            int flag = calendar.get(Calendar.DAY_OF_WEEK); // 获得礼拜几信息
            // 获得当前礼拜
            calendar.add(Calendar.DAY_OF_YEAR, -flag + 2);
            date = calendar.getTime();
            result[0] = sDateFormat.format(date); // 礼拜一
            for (int i = 0; i < 6; i++) {
                calendar.add(Calendar.DAY_OF_YEAR, 1);
                date = calendar.getTime();
                result[i + 1] = sDateFormat.format(date); // 礼拜2...
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据datestr指定的日期获取星期,星期天用7表示
     *
     * @param datestr 日期
     */
    public static Integer getDayOfWeek(String datestr) {
        Integer result = 1;
        Calendar calendar = Calendar.getInstance(); // 创建日历实例,默认当前日期
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 设置日期格式
        try {
            Date date = sDateFormat.parse(datestr);

            calendar.setTime(date);
            int flag = calendar.get(Calendar.DAY_OF_WEEK); // 获得礼拜几信息
            if (flag == 1) {
                flag = 8;
            }
            result = flag - 1;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据datestr指定的日期获取星期
     *
     * @param datestr 日期
     */
    public static String getDayOfWeekStr(String datestr) {
        String[] weeks = new String[]{" ", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
        Integer week = getDayOfWeek(datestr);
        return weeks[week];
    }

    /**
     * 根据datestr指定的日期获取属于当年第几周
     *
     * @param datestr 日期
     */
    public static Integer getWeekOfYear(String datestr) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = format.parse(datestr);
            Calendar calendar = Calendar.getInstance();
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            calendar.setTime(date);
            return calendar.get(Calendar.WEEK_OF_YEAR);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 以字符串形式返回下周一和下周日的日期
     */
    public static String[] nextMonday() throws ParseException {
        String[] str = new String[2];
        Date ks = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String riqi = "";
        Calendar cal = Calendar.getInstance();
        if (cal.get(Calendar.DAY_OF_WEEK) != 0) {
            riqi = formatter.format(new Date(ks.getTime() + 1000 * 3600 * 24 * 7));
        } else {
            riqi = formatter.format(ks);
        }
        Calendar as = Calendar.getInstance();
        as.setTime(formatter.parse(riqi));
        as.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        str[0] = formatter.format(as.getTime());
        str[1] = formatter.format(new Date(as.getTime().getTime() + 1000 * 3600 * 24 * 6));
        return str;
    }
}

缺少的枚举在上面

package org.tool.demo.util;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class DateUtils {

    public static String dateString(Long time) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);
        Date time1 = c.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String str = sdf.format(time1);
        return str;
    }

    public static String dateToString(Long time) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);
        Date time1 = c.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String str = sdf.format(time1);
        return str;
    }

    /**
     * 将String型转为Date型
     *
     * @param value
     * @param format
     * @return format || yyyy-MM-dd
     */
    public static Date convertDate(String value, String format) {
        if (StringUtils.isBlank(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        if (StringUtils.isNotBlank(value)) {
            try {
                return sdf.parse(value);
            } catch (ParseException e) {
//                log.error("time convertDate error:{}", e);
            }
        }
        return null;
    }

    /**
     * 将String型转为Date型
     *
     * @param value
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static Date convertDateYMDHMS(String value) {
        return convertDate(value, "yyyy-MM-dd HH:mm:ss");
    }

    public static String getCurrentTimeStr() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssS");
        return sdf.format(new Date());
    }

    public static Date getDate(Long mseconds) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(mseconds);
        return date;
    }

    /**
     * 将Date型转为String型
     *
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String formatDateYMDHMS(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 将Date型转为String型
     *
     * @param date
     * @param format
     * @return format || null
     */
    public static String formatDate(Date date, String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * 获取当前类型开始时间
     * @return
     */
    public static String getStartDateTime(DateEnum dateEnum){
        switch (dateEnum.getValue()){
            case "day":
                return getStartDayTime();
            case "week":
                return getStartWeekTime();
            case "month":
                return getStartMonthDate();
            default:
                return "";
        }
    }


    /**
     * 获取当前类型结束时间
     * @return
     */
    public static String getEndDateTime(DateEnum dateEnum){
        switch (dateEnum.getValue()){
            case "day":
                return getEndDayTime();
            case "week":
                return getEndWeekTime();
            case "month":
                return getEndMonthDate();
            default:
                return "";
        }
    }

    /**
     * 当天开始时间
     * @return
     */
    private static String getStartDayTime() {
        Calendar dateStart = Calendar.getInstance();
        dateStart.setTime(new Date());
        dateStart.set(Calendar.HOUR_OF_DAY, 0);
        dateStart.set(Calendar.MINUTE, 0);
        dateStart.set(Calendar.SECOND, 0);
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(dateStart.getTime());
    }

    /**
     * 当天结束时间
     * @return
     */
    private static String getEndDayTime() {
        Calendar dateStart = Calendar.getInstance();
        dateStart.setTime(new Date());
        dateStart.set(Calendar.HOUR_OF_DAY, 23);
        dateStart.set(Calendar.MINUTE, 59);
        dateStart.set(Calendar.SECOND, 59);
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(dateStart.getTime());
    }

    /**
     * 本周开始时间
     * @return
     */
    private static String getStartWeekTime() {
        Calendar dateStart = Calendar.getInstance();
        dateStart.setTime(new Date());
        dateStart.setFirstDayOfWeek(Calendar.MONDAY);
        dateStart.set(Calendar.HOUR_OF_DAY, 0);
        dateStart.set(Calendar.MINUTE, 0);
        dateStart.set(Calendar.SECOND, 0);
        dateStart.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(dateStart.getTime());
    }

    /**
     * 本周结束时间
     * @return
     */
    private static String getEndWeekTime() {
        Calendar dateStart = Calendar.getInstance();
        dateStart.setTime(new Date());
        dateStart.setFirstDayOfWeek(Calendar.MONDAY);
        dateStart.set(Calendar.HOUR_OF_DAY, 23);
        dateStart.set(Calendar.MINUTE, 59);
        dateStart.set(Calendar.SECOND, 59);
        dateStart.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(dateStart.getTime());
    }

    /**
     * 本月开始时间
     * @return
     */
    private static String getStartMonthDate() {
        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        try {
            calendar.setTime(new Date());
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            return dateFormat.format(calendar.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 本月结束时间
     * @return
     */
    private static String getEndMonthDate() {
        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        try {
            calendar.setTime(new Date());
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            return dateFormat.format(calendar.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断当前时间是昨天、今天、还是其他时间
     * @param currentTimeMillis
     * @return
     */
    public static String getCurrentDayTime(Long currentTimeMillis, Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String paramDate = dateFormat.format(date);
        String[] paramDateSplit = paramDate.split("-");
        Integer paramDateMonth = Integer.valueOf(paramDateSplit[1]);
        Integer paramDateDay = Integer.valueOf(paramDateSplit[2]);

        Date systemDate = new Date(currentTimeMillis);
        String format = dateFormat.format(systemDate);
        String[] systemDateSplit = format.split("-");
        Integer currentMonth = Integer.valueOf(systemDateSplit[1]);
        Integer currentDay = Integer.valueOf(systemDateSplit[2]);

        if (currentMonth == paramDateMonth) {
            if (currentDay == paramDateDay)  {
                return "今天";
            } else if (currentDay == paramDateDay + 1){
                return "昨天";
            } else {
                return paramDate;
            }
        } else {
            //上一个月的最后一天的日
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH, 0);
            Date lastDayOfPreviousMonth = calendar.getTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd");
            String lastDay = simpleDateFormat.format(lastDayOfPreviousMonth);
            if (currentDay == 1 && paramDateDay == Integer.valueOf(lastDay)) {
                return "昨天";
            }
            return paramDate;
        }
    }
}



2 String

package org.tool.demo.util;

import org.springframework.util.StringUtils;

import java.util.regex.Pattern;

public class StringUtil {
    private final static Pattern egtZeroPattern = Pattern.compile("([0-9]\\d*(\\.\\d*[0-9])?)");
    private final static Pattern isEZ = Pattern.compile("^([1-9]\\d*(\\.\\d*[1-9][0-9])?)|(0\\.\\d*[1-9][0-9])|(0\\.\\d*[1-9])$");

    /**
     * 根据style获取宽
     *
     * @param style
     * @return
     */
    public static Integer getWidthByStyle(String style) {
        if (StringUtils.isEmpty(style)) {
            return null;
        }
        String width = style.substring(style.lastIndexOf("w_") + 2);
        if (width.indexOf(",") > 0) {
            width = width.substring(0, width.indexOf(","));
        }
        return Integer.parseInt(width);
    }

    /**
     * 根据style获取高
     *
     * @param style
     * @return
     */
    public static Integer getHeightByStyle(String style) {
        if (StringUtils.isEmpty(style)) {
            return null;
        }
        String height = style.substring(style.lastIndexOf("h_") + 2);
        if (height.indexOf(",") > 0) {
            height = height.substring(0, height.indexOf(","));
        }
        return Integer.parseInt(height);
    }


    /**
     * 判断是否是英文
     * @param charaString
     * @return
     */
    public static boolean isEnglish(String charaString){

        charaString = charaString.replaceAll(" ","");
        charaString = charaString.replaceAll("-","");

        return charaString.matches("^[a-zA-Z]*");

    }

    /**
     * 判断字符串是不是纯数字
     */
    public static Boolean sNumber(String string){
        return string.matches("[0-9]+");
    }


    /**
     * 校验大于等零的数
     *
     * @param string
     * @return true 大于等零
     */
    public static boolean isEgtZero(String string) {
        if(StringUtils.isEmpty(string)){
            return false;
        }
        return egtZeroPattern.matcher(string).matches();
    }

    /**
     * 去除首尾固定字符
     * @param srcStr
     * @param splitter
     * @return
     */
    public static String trimBothEndsChars(String srcStr, String splitter) {
        String regex = "^" + splitter + "*|" + splitter + "*$";
        return srcStr.replaceAll(regex, "");
    }

}

3 redis

package org.tool.demo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {


    public static final String APP_REDIS_KEY = "xxxx-read:";

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

    @Autowired
    StringRedisTemplate redisTemplate;



    public boolean setNx(String key, String value,Long time,TimeUnit timeUnit) {
        key = APP_REDIS_KEY + key;
        return redisTemplate.opsForValue().setIfAbsent(key,value,time,timeUnit);
    }

    public void setListRightPush(String key, String value) {
        key = APP_REDIS_KEY + key;
        redisTemplate.opsForList().rightPush(key,value);
    }

    public String getListLeftPop(String key) {
        key = APP_REDIS_KEY + key;
        return redisTemplate.opsForList().leftPop(key);
    }
    public String getListByIndex(String key,long index) {
        key = APP_REDIS_KEY + key;
        return redisTemplate.opsForList().index(key,index);
    }

    public void set(String key, String value) {
        key = APP_REDIS_KEY + key;
        logger.info("redis set key {}", key);
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(String key, String value, long timeout, TimeUnit unit) {
        key = APP_REDIS_KEY + key;
        logger.info("redis set key {}", key);
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public Boolean del(String key) {
        key = APP_REDIS_KEY + key;
        logger.info("redis del key {}", key);
        return redisTemplate.delete(key);
    }

    public Long del(List<String> keys) {
        keys.forEach(k -> keys.set(keys.indexOf(k),APP_REDIS_KEY + k));
        logger.info("redis del key {}", keys);
        return redisTemplate.delete(keys);
    }

    public String get(String key) {
        key = APP_REDIS_KEY + key;
        return redisTemplate.opsForValue().get(key);
    }

    public void set(String key, String hashKey, String value) {
        key = APP_REDIS_KEY + key;
        logger.info("redis set key {}, hashKey {}", key, hashKey);
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    public void setExpire(String key, long timeout,TimeUnit unit){
        key = APP_REDIS_KEY + key;
        logger.info("redis set key {}", key);
        redisTemplate.expire(key, timeout, unit);
    }

    public void del(String key, String hashKey) {
        key = APP_REDIS_KEY + key;
        logger.info("redis del key {}, hashKey {}", key, hashKey);
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    public Object get(String key, String hashKey) {
        key = APP_REDIS_KEY + key;
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    public Set<Object> keys(String key) {
        key = APP_REDIS_KEY + key;
        return redisTemplate.opsForHash().keys(key);
    }




    public void setKeyByEvaluationContent(Long planId, Long courseId,Long stuId, String key, String content){
        if (Objects.isNull(courseId)){
            key = String.format(key, planId, stuId);
        }else {
            key = String.format(key, planId, courseId, stuId);
        }

        this.set(key, content, 150L, TimeUnit.SECONDS);
    }

    public void delKeyByEvaluation(Long planId,Long courseId, Long stuId, String key){
        if (Objects.isNull(courseId)){
            key = String.format(key, planId, stuId);
        }else {
            key = String.format(key, planId, courseId, stuId);
        }
        this.del(key);
    }

    public void setExpireByEvaluation(Long planId,Long courseId, Long stuId, String key){
        if (Objects.isNull(courseId)){
            key = String.format(key, planId, stuId);
        }else {
            key = String.format(key, planId, courseId, stuId);
        }
        this.setExpire(key, 150L, TimeUnit.SECONDS);
    }

}

4 redirectUtil

重定向工具

package org.tool.demo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class RedirectUtil {
    private Logger logger = LoggerFactory.getLogger(RedirectUtil.class);
    /**
     * @Method 预览图 跳转oss previewProblemFile
     * @Exception
     * @Date 
     */
    public void redirectPreviewProblemFile(HttpServletResponse response) {
        try {
            response.sendRedirect("https://xxxxxxx.oss-cn-hangzhou.aliyuncs.com/preview/heic-conver.png");
            return;
        } catch (IOException ex) {
            logger.error(ex.getMessage());
            //如果样式导致的异常,去掉样式在处理一遍
        }
        return;
    }

    /**
     * @Method 预览图 跳转oss previewNoPreview
     * @Exception
     * @Date 
     */
    public void redirectPreviewNoPreview(HttpServletResponse response) {
        try {
            response.sendRedirect("https://xxxxxx.oss-cn-hangzhou.aliyuncs.com/preview/no-preview.png");
            return;
        } catch (IOException ex) {
            logger.error(ex.getMessage());
            //如果样式导致的异常,去掉样式在处理一遍
        }
        return;
    }
    /**
     * @Method 预览图 跳转oss previewVideoPicPath
     * @Exception
     * @Date
     */
    public void redirectPreviewVideoPicPath(HttpServletResponse response) {
        try {
            response.sendRedirect("https://xxxxxx.oss-cn-hangzhou.aliyuncs.com/readFile/audio.png");
            return;
        } catch (IOException ex) {
            logger.error(ex.getMessage());
            //如果样式导致的异常,去掉样式在处理一遍
        }
        return;
    }

}

5 Http请求工具

自己提供的接口需要调用第三方接口的时候,需要在本接口内发送http请求以获取第三方返回的数据,此时可以使用如下

package org.yungu.read.common.utils;

import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;

/**
 * @program: yungu-read
 * @description: HTTP请求工具类
 * @author: yunlong
 * @create: 2022-03-02 15:48
 **/
public class HttpKit {

    private static final String GET = "GET";
    private static final String POST = "POST";
    private static String CHARSET = "UTF-8";
    private static int connectTimeout = 19000;
    private static int readTimeout = 19000;
    private static final SSLSocketFactory sslSocketFactory = initSSLSocketFactory();
    private static final HttpKit.TrustAnyHostnameVerifier trustAnyHostnameVerifier = new HttpKit.TrustAnyHostnameVerifier();

    private HttpKit() {
    }

    private static SSLSocketFactory initSSLSocketFactory() {
        try {
            TrustManager[] tm = new TrustManager[]{new HttpKit.TrustAnyTrustManager()};
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init((KeyManager[])null, tm, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception var2) {
            throw new RuntimeException(var2);
        }
    }

    public static void setCharSet(String charSet) {
        if (StringUtils.isEmpty(charSet)) {
            throw new IllegalArgumentException("charSet can not be blank.");
        } else {
            CHARSET = charSet;
        }
    }

    public static void setConnectTimeout(int connectTimeout) {
        HttpKit.connectTimeout = connectTimeout;
    }

    public static void setReadTimeout(int readTimeout) {
        HttpKit.readTimeout = readTimeout;
    }

    private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        URL _url = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)_url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            ((HttpsURLConnection)conn).setSSLSocketFactory(sslSocketFactory);
            ((HttpsURLConnection)conn).setHostnameVerifier(trustAnyHostnameVerifier);
        }

        conn.setRequestMethod(method);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(connectTimeout);
        conn.setReadTimeout(readTimeout);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
        if (headers != null && !headers.isEmpty()) {
            Iterator var5 = headers.entrySet().iterator();

            while(var5.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry)var5.next();
                conn.setRequestProperty((String)entry.getKey(), (String)entry.getValue());
            }
        }

        return conn;
    }

    public static String get(String url, Map<String, String> queryParas, Map<String, String> headers) {
        HttpURLConnection conn = null;

        String var4;
        try {
            conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), "GET", headers);
            conn.connect();
            var4 = readResponseString(conn);
        } catch (Exception var8) {
            throw new RuntimeException(var8);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }

        }

        return var4;
    }

    public static String get(String url, Map<String, String> queryParas) {
        return get(url, queryParas, (Map)null);
    }

    public static String get(String url) {
        return get(url, (Map)null, (Map)null);
    }

    public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) {
        HttpURLConnection conn = null;

        String var11;
        try {
            conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), "POST", headers);
            conn.connect();
            if (data != null) {
                OutputStream out = conn.getOutputStream();
                out.write(data.getBytes(CHARSET));
                out.flush();
                out.close();
            }

            var11 = readResponseString(conn);
        } catch (Exception var9) {
            throw new RuntimeException(var9);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }

        }

        return var11;
    }

    public static String post(String url, Map<String, String> queryParas, String data) {
        return post(url, queryParas, data, (Map)null);
    }

    public static String post(String url, String data, Map<String, String> headers) {
        return post(url, (Map)null, data, headers);
    }

    public static String post(String url, String data) {
        return post(url, (Map)null, data, (Map)null);
    }

    private static String readResponseString(HttpURLConnection conn) {
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), CHARSET));
            String line = reader.readLine();
            String var4;
            if (line == null) {
                var4 = "";
                return var4;
            } else {
                StringBuilder ret = new StringBuilder();
                ret.append(line);

                while((line = reader.readLine()) != null) {
                    ret.append('\n').append(line);
                }

                var4 = ret.toString();
                return var4;
            }
        } catch (Exception var14) {
            throw new RuntimeException(var14);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException var13) {
                    throw new RuntimeException(var13.getMessage());
                }
            }

        }
    }

    private static String buildUrlWithQueryString(String url, Map<String, String> queryParas) {
        if (queryParas != null && !queryParas.isEmpty()) {
            StringBuilder sb = new StringBuilder(url);
            boolean isFirst;
            if (url.indexOf(63) == -1) {
                isFirst = true;
                sb.append('?');
            } else {
                isFirst = false;
            }

            String key;
            String value;
            for(Iterator var4 = queryParas.entrySet().iterator(); var4.hasNext(); sb.append(key).append('=').append(value)) {
                Map.Entry<String, String> entry = (Map.Entry)var4.next();
                if (isFirst) {
                    isFirst = false;
                } else {
                    sb.append('&');
                }

                key = (String)entry.getKey();
                value = (String)entry.getValue();
                if (StringUtils.isNotEmpty(value)) {
                    try {
                        value = URLEncoder.encode(value, CHARSET);
                    } catch (UnsupportedEncodingException var9) {
                        throw new RuntimeException(var9);
                    }
                }
            }

            return sb.toString();
        } else {
            return url;
        }
    }

    public static String readData(HttpServletRequest request) {
        BufferedReader br = null;

        try {
            br = request.getReader();
            String line = br.readLine();
            if (line == null) {
                return "";
            } else {
                StringBuilder ret = new StringBuilder();
                ret.append(line);

                while((line = br.readLine()) != null) {
                    ret.append('\n').append(line);
                }

                return ret.toString();
            }
        } catch (IOException var4) {
            throw new RuntimeException(var4);
        }
    }

    /** @deprecated */
    @Deprecated
    public static String readIncommingRequestData(HttpServletRequest request) {
        return readData(request);
    }

    public static boolean isHttps(HttpServletRequest request) {
        return "https".equalsIgnoreCase(request.getHeader("X-Forwarded-Proto")) || "https".equalsIgnoreCase(request.getScheme());
    }

    private static class TrustAnyTrustManager implements X509TrustManager {
        private TrustAnyTrustManager() {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        private TrustAnyHostnameVerifier() {
        }

        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
}

6  cookie

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 *
 * Cookie 工具类
 *
 */
public final class CookieUtils {

	static final Logger logger = LoggerFactory.getLogger(CookieUtils.class);

	/**
	 * 得到Cookie的值, 不编码
	 *
	 * @param request
	 * @param cookieName
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request, String cookieName) {
		return getCookieValue(request, cookieName, false);
	}

	/**
	 * 得到Cookie的值,
	 *
	 * @param request
	 * @param cookieName
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
		Cookie[] cookieList = request.getCookies();
		if (cookieList == null || cookieName == null){
			return null;
		}
		String retValue = null;
		try {
			for (int i = 0; i < cookieList.length; i++) {
				if (cookieList[i].getName().equals(cookieName)) {
					if (isDecoder) {
						retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
					} else {
						retValue = cookieList[i].getValue();
					}
					break;
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("Cookie Decode Error.", e);
		}
		return retValue;
	}

	/**
	 * 得到Cookie的值,
	 *
	 * @param request
	 * @param cookieName
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
		Cookie[] cookieList = request.getCookies();
		if (cookieList == null || cookieName == null){
			return null;
		}
		String retValue = null;
		try {
			for (int i = 0; i < cookieList.length; i++) {
				if (cookieList[i].getName().equals(cookieName)) {
					retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
					break;
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("Cookie Decode Error.", e);
		}
		return retValue;
	}

	/**
	 * 生成cookie,并指定编码
	 * @param request 请求
	 * @param response 响应
	 * @param cookieName name
	 * @param cookieValue value
	 * @param encodeString 编码
	 */
	public static final void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, String encodeString) {
		setCookie(request,response,cookieName,cookieValue,null,encodeString, null);
	}

	/**
	 * 生成cookie,并指定生存时间
	 * @param request 请求
	 * @param response 响应
	 * @param cookieName name
	 * @param cookieValue value
	 * @param cookieMaxAge 生存时间
	 */
	public static final void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, Integer cookieMaxAge) {
		setCookie(request,response,cookieName,cookieValue,cookieMaxAge,null, null);
	}

	/**
	 * 设置cookie,不指定httpOnly属性
	 */
	public static final void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, Integer cookieMaxAge, String encodeString) {
		setCookie(request,response,cookieName,cookieValue,cookieMaxAge,encodeString, null);
	}

	/**
	 * 设置Cookie的值,并使其在指定时间内生效
	 *
	 * @param cookieMaxAge
	 *            cookie生效的最大秒数
	 */
	public static final void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, Integer cookieMaxAge, String encodeString, Boolean httpOnly) {
		try {
			if(StringUtils.isBlank(encodeString)) {
				encodeString = "utf-8";
			}

			if (cookieValue == null) {
				cookieValue = "";
			} else {
				cookieValue = URLEncoder.encode(cookieValue, encodeString);
			}
			Cookie cookie = new Cookie(cookieName, cookieValue);
			if (cookieMaxAge != null && cookieMaxAge > 0)
				cookie.setMaxAge(cookieMaxAge);
			if (null != request)// 设置域名的cookie
				cookie.setDomain(getDomainName(request));
			cookie.setPath("/");

			if(httpOnly != null) {
				cookie.setHttpOnly(httpOnly);
			}
			response.addCookie(cookie);
		} catch (Exception e) {
			logger.error("Cookie Encode Error.", e);
		}
	}

	/**
	 * 得到cookie的域名
	 */
	private static final String getDomainName(HttpServletRequest request) {
		String domainName = null;

//		String serverName = request.getRequestURL().toString();
		String serverName = request.getHeader("X-Forwarded-Host");

		if (serverName == null || serverName.equals("")) {
			domainName = "";
		} else {
			serverName = serverName.toLowerCase();
//			serverName = serverName.substring(7);
//			final int end = serverName.indexOf("/");
//			serverName = serverName.substring(0, end);
			final String[] domains = serverName.split("\\.");
			int len = domains.length;
			if (len > 3) {
				// www.xxx.com.cn
				domainName = domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
			} else if (len <= 3 && len > 1) {
				// xxx.com or xxx.cn
				domainName = domains[len - 2] + "." + domains[len - 1];
			} else {
				domainName = serverName;
			}
		}

		if (domainName != null && domainName.indexOf(":") > 0) {
			String[] ary = domainName.split("\\:");
			domainName = ary[0];
		}
		return domainName;
	}

}

7 jwt

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.10.6</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.10.6</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.10.6</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.3</version>
</dependency>

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Map;

public class JwtUtils {
    /**
     * 私钥加密token
     *
     * @param map           载荷中的数据
     * @param expireMinutes 过期时间,单位秒
     * @return
     * @throws Exception
     */
    public static String generateToken(Map<String, Object> map, PrivateKey key, int expireMinutes) throws Exception {
        return Jwts.builder()
                .setClaims(map)
                .setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
                .signWith(key, SignatureAlgorithm.RS256)
                .compact();
    }

    /**
     * 公钥解析token
     *
     * @param token  用户请求中的token
     * @return
     * @throws Exception
     */
    private static Jws<Claims> parserToken(String token, PublicKey key) {
        return Jwts.parser().setSigningKey(key).parseClaimsJws(token);
    }

    /**
     * 获取token中的用户信息
     *
     * @param token  用户请求中的令牌
     * @return 用户信息
     * @throws Exception
     */
    public static Map<String, Object> getInfoFromToken(String token, PublicKey key) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, key);
        return claimsJws.getBody();
    }

}

8 RSA

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RsaUtils {
    /**
     * 从文件中读取公钥
     *
     * @param filename 公钥保存路径,相对于classpath
     * @return 公钥对象
     * @throws Exception
     */
    public static PublicKey getPublicKey(String filename) throws Exception {
        byte[] bytes = readFile(filename);
        return getPublicKey(bytes);
    }

    /**
     * 从文件中读取密钥
     *
     * @param filename 私钥保存路径,相对于classpath
     * @return 私钥对象
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String filename) throws Exception {
        byte[] bytes = readFile(filename);
        return getPrivateKey(bytes);
    }

    /**
     * 获取公钥
     *
     * @param bytes 公钥的字节形式
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(byte[] bytes) throws Exception {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePublic(spec);
    }

    /**
     * 获取密钥
     *
     * @param bytes 私钥的字节形式
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(byte[] bytes) throws Exception {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePrivate(spec);
    }

    /**
     * 根据密文,生存rsa公钥和私钥,并写入指定文件
     *
     * @param publicKeyFilename  公钥文件路径
     * @param privateKeyFilename 私钥文件路径
     * @param secret             生成密钥的密文
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom secureRandom = new SecureRandom(secret.getBytes());
        keyPairGenerator.initialize(2048, secureRandom);
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        // 获取公钥并写出
        byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
        writeFile(publicKeyFilename, publicKeyBytes);
        // 获取私钥并写出
        byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
        writeFile(privateKeyFilename, privateKeyBytes);
    }

    private static byte[] readFile(String fileName) throws Exception {
        return Files.readAllBytes(new File(fileName).toPath());
    }

    private static void writeFile(String destPath, byte[] bytes) throws IOException {
        File dest = new File(destPath);
        if (!dest.exists()) {
            dest.createNewFile();
        }
        Files.write(dest.toPath(), bytes);
    }
}

四 实体类

五返回结果集类

1 第一种

package org.tool.demo.util;


import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.io.Serializable;

/**
 * @author yuxi.wyx
 */
public class BaseResultModel<T> implements Serializable {
    private static final long serialVersionUID = -8977845725981280355L;

    /**
     * 是否成功
     */
    private boolean status;
    /**
     * 消息
     */
    private String message;
    /**
     * 请求返回状态码
     */
    private Integer code;
    /**
     * 数据
     */
    private T content;
    /**
     * 是否登陆
     * todo 临时添加。之前没有
     */
    private Boolean ifLogin;

    private boolean ifAdmin;

    public BaseResultModel() {

    }

    public BaseResultModel(boolean status, String message, Integer code, T content, boolean loginStatus) {
        this.status = status;
        this.message = message;
        this.code = code;
        this.content = content;
        this.ifLogin = loginStatus;
    }

    public static <T> BaseResultModel<T> buildSuccess(String description, int messageCode, T content) {
        return new BaseResultModel<T>(true, description, messageCode, content, true);
    }

    public static <T> BaseResultModel<T> buildSuccess(CodeEnum codeEnum, T content) {
        return buildSuccess(codeEnum.getDescription(), codeEnum.getMessageCode(), content);
    }

    public static <T> BaseResultModel<T> buildSuccess(T content) {
        return buildSuccess(CodeEnum.SUCCESS_CODE, content);
    }

    public static <T> BaseResultModel<T> buildSuccess() {
        return buildSuccess(CodeEnum.SUCCESS_CODE, null);
    }

    public static <T> BaseResultModel<T> buildFail(String description, int messageCode, T content) {
        return new BaseResultModel<T>(false, description, messageCode, content, true);
    }

    public static <T> BaseResultModel<T> buildFail(CodeEnum codeEnum, T content) {
        return buildFail(codeEnum.getDescription(), codeEnum.getMessageCode(), content);
    }

    public static <T> BaseResultModel<T> buildFail(CodeEnum codeEnum) {
        return buildFail(codeEnum.getDescription(), codeEnum.getMessageCode(), null);
    }

    public static <T> BaseResultModel<T> buildFail() {
        return buildFail(CodeEnum.FALSE_CODE,null);
    }

    public static <T> BaseResultModel<T> buildResult(boolean status) {
        CodeEnum codeEnum = CodeEnum.FALSE_CODE;
        if (status) {
            codeEnum = CodeEnum.SUCCESS_CODE;
        }
        return new BaseResultModel<T>(status, codeEnum.getDescription(), codeEnum.getMessageCode(), null, true);
    }


    public boolean isIfAdmin() {
        return ifAdmin;
    }

    public void setIfAdmin(boolean ifAdmin) {
        this.ifAdmin = ifAdmin;
    }

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public T getContent() {
        return content;
    }

    public void setContent(T content) {
        this.content = content;
    }

    public Boolean getIfLogin() {
        return ifLogin;
    }

    public void setIfLogin(Boolean ifLogin) {
        this.ifLogin = ifLogin;
    }

    public boolean isSuccess(){
        if( code == null) {
            return false;
        }
        return  code.equals(CodeEnum.SUCCESS_CODE.getMessageCode());
    }

    public boolean isFail(){
        return !isSuccess();
    }
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE);
    }
}

牵扯的枚举

package org.tool.demo.util;


/**
 * 基础返回模型 code和说明
 */
public enum CodeEnum {
    /**
     * 基础返回模型 code和说明
     * 备注:ipad端的需要,为了复用代码,成功的状态码需要是0
     */
    SUCCESS_CODE(0, "成功"),
    FALSE_CODE(1, "操作失败"),
    SYSTEM_BUSY(2, "系统繁忙"),

    //5000开始记录阅读详情相关的状态
    READ_DETAIL_EMPTY(5000, "查询打卡记录为空"),
    READ_DATE_CANT_EMPTY(5001, "查询打卡日期不能为空"),
    CANT_NOT_EDIT_READ_DETAIL(5002, "不可以编辑别人的打卡记录"),
    READ_DETAIL_ID_EMPTY(5003,"阅读记录id参数缺失"),
    ADD_READ_DETAIL_FAILE(5004, "添加阅读记录失败"),
    ADD_OR_UPRATE_READ_DETAIL_FAILE(5005, "添加或者更新阅读记录失败"),
    ;
    private int messageCode;
    private String description;

    CodeEnum(int messageCode, String description) {
        this.description = description;
        this.messageCode = messageCode;
    }

    public int getMessageCode() {
        return messageCode;
    }

    public void setMessageCode(int messageCode) {
        this.messageCode = messageCode;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

六 配置类

1aop切面类

2 filter过滤类

3  拦截器类

4 监听器类

有空在完善

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值