package com.id0304.utils;
import java.security.MessageDigest;
/**
* Created by codermen on 2017/10/26.
*/
public class Md5Util {
//生成MD5
public static String getMD5(String message) {
String md5 = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5"); // 创建一个md5算法对象
byte[] messageByte = message.getBytes("UTF-8");
byte[] md5Byte = md.digest(messageByte); // 获得MD5字节数组,16*8=128位
md5 = bytesToHex(md5Byte); // 转换为16进制字符串
} catch (Exception e) {
e.printStackTrace();
}
return md5;
}
// 二进制转十六进制
public static String bytesToHex(byte[] bytes) {
StringBuffer hexStr = new StringBuffer();
int num;
for (int i = 0; i < bytes.length; i++) {
num = bytes[i];
if (num < 0) {
num += 256;
}
if (num < 16) {
hexStr.append("0");
}
hexStr.append(Integer.toHexString(num));
}
return hexStr.toString().toUpperCase();
}
}
package com.id0304.utils;
import java.io.*;
public final class Base64Util
{
private static final int BASELENGTH = 255;
private static final int LOOKUPLENGTH = 64;
private static final int TWENTYFOURBITGROUP = 24;
private static final int EIGHTBIT = 8;
private static final int SIXTEENBIT = 16;
// private static final int SIXBIT = 6;
private static final int FOURBYTE = 4;
// private static final int TWOBYTE = 2;
private static final int SIGN = -128;
private static final byte PAD = (byte) '=';
private static byte[] base64Alphabet = new byte[BASELENGTH];
private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
static
{
for (int i = 0; i < BASELENGTH; i++)
{
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--)
{
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--)
{
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--)
{
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++)
{
lookUpBase64Alphabet[i] = (byte) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++)
{
lookUpBase64Alphabet[i] = (byte) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++)
{
lookUpBase64Alphabet[i] = (byte) ('0' + j);
}
lookUpBase64Alphabet[62] = (byte) '+';
lookUpBase64Alphabet[63] = (byte) '/';
}
public static boolean isBase64(String isValidString)
{
return isArrayByteBase64(isValidString.getBytes());
}
public static boolean isBase64(byte octect)
{
// shall we ignore white space? JEFF??
return (octect == PAD || base64Alphabet[octect] != -1);
}
public static boolean isArrayByteBase64(byte[] arrayOctect)
{
int length = arrayOctect.length;
if (length == 0)
{
// shouldn't a 0 length array be valid base64 data?
// return false;
return true;
}
for (int i = 0; i < length; i++)
{
if (!isBase64(arrayOctect[i]))
{
return false;
}
}
return true;
}
/**
* Encode String object;
*
* @param src String object to be encoded.
* @return encoded String;
*/
public static String encodeString(String src)
{
return encode(src);
}
public static String encodeBytes(byte[] src)
{
if (src == null || src.length == 0) {
return null;
}
byte[] bytes = encode(src);
return new String(bytes);
}
/**
* Encode String object;
*
* @param src String object to be encoded.
* @return encoded String;
*/
public static String encode(String src)
{
String target = null;
if (src != null)
{
byte[] bts1 = src.getBytes();
byte[] bts2 = encode(bts1);
if (bts2 != null)
{
target = new String(bts2);
}
}
return target;
}
/**
* Encodes hex octects into Base64.
*
* @param binaryData Array containing binary data to encode.
* @return Base64-encoded data.
*/
public static byte[] encode(byte[] binaryData)
{
int lengthDataBits = binaryData.length * EIGHTBIT;
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
byte encodedData[] = null;
if (fewerThan24bits != 0)
{
// data not divisible by 24 bit
encodedData = new byte[(numberTriplets + 1) * 4];
}
else
{
// 16 or 8 bit
encodedData = new byte[numberTriplets * 4];
}
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
int i = 0;
for (i = 0; i < numberTriplets; i++)
{
dataIndex = i * 3;
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
b3 = binaryData[dataIndex + 2];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
encodedIndex = i * 4;
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
dataIndex = i * 3;
encodedIndex = i * 4;
if (fewerThan24bits == EIGHTBIT)
{
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex + 2] = PAD;
encodedData[encodedIndex + 3] = PAD;
}
else if (fewerThan24bits == SIXTEENBIT)
{
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex + 3] = PAD;
}
return encodedData;
}
public static String decode(String src)
{
String target = null;
if (src != null)
{
byte[] bts1 = src.getBytes();
byte[] bts2 = decode(bts1);
if (bts2 != null)
{
target = new String(bts2);
}
}
return target;
}
public static String decode(String src, String charSet) throws UnsupportedEncodingException
{
String target = null;
if (src != null)
{
byte[] bts1 = src.getBytes();
byte[] bts2 = decode(bts1);
if (bts2 != null)
{
target = new String(bts2, charSet);
}
}
return target;
}
/**
* Decodes Base64 data into octects
*
* @param base64Data Byte array containing Base64 data
* @return Array containing decoded data.
*/
public static byte[] decode(byte[] base64Data)
{
// handle the edge case, so we don't have to worry about it later
if (base64Data.length == 0)
{
return null;
}
int numberQuadruple = base64Data.length / FOURBYTE;
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
// Throw away anything not in base64Data
int encodedIndex = 0;
int dataIndex = 0;
{
// this sizes the output array properly - rlw
int lastData = base64Data.length;
// ignore the '=' padding
while (base64Data[lastData - 1] == PAD)
{
if (--lastData == 0)
{
return new byte[0];
}
}
decodedData = new byte[lastData - numberQuadruple];
}
for (int i = 0; i < numberQuadruple; i++)
{
dataIndex = i * 4;
marker0 = base64Data[dataIndex + 2];
marker1 = base64Data[dataIndex + 3];
b1 = base64Alphabet[base64Data[dataIndex]];
b2 = base64Alphabet[base64Data[dataIndex + 1]];
if (marker0 != PAD && marker1 != PAD)
{
// No PAD e.g 3cQl
b3 = base64Alphabet[marker0];
b4 = base64Alphabet[marker1];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
}
else if (marker0 == PAD)
{
// Two PAD e.g. 3c[Pad][Pad]
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
}
else if (marker1 == PAD)
{
// One PAD e.g. 3cQ[Pad]
b3 = base64Alphabet[marker0];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
}
encodedIndex += 3;
}
return decodedData;
}
/**
* 隐藏工具类的构造方法
*/
protected Base64Util()
{
throw new UnsupportedOperationException();
}
/**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;
/** *//**
*
* BASE64字符串解码为二进制数据
*
*
* @param base64
* @return
* @throws Exception
*/
public static byte[] decodeString(String base64) throws Exception {
return Base64Util.decode(base64.getBytes());
}
/** *//**
*
* 二进制数据编码为BASE64字符串
*
*
* @param bytes
* @return
* @throws Exception
*/
public static String encodeByte(byte[] bytes) throws Exception {
return new String(Base64Util.encode(bytes));
}
/** *//**
*
* 将文件编码为BASE64字符串
*
*
* 大文件慎用,可能会导致内存溢出
*
*
* @param filePath 文件绝对路径
* @return
* @throws Exception
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encodeByte(bytes);
}
/** *//**
*
* BASE64字符串转回文件
*
*
* @param filePath 文件绝对路径
* @param base64 编码字符串
* @throws Exception
*/
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decodeString(base64);
byteArrayToFile(bytes, filePath);
}
/** *//**
*
* 文件转换为二进制数组
*
*
* @param filePath 文件路径
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
/** *//**
*
* 二进制数据写文件
*
*
* @param bytes 二进制数据
* @param filePath 文件生成目录
*/
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
}
}
package com.id0304.utils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Cookie工具类
*
*/
public class CookieUtil {
private CookieUtil() {
}
/**
* 添加cookie
*
* @param response
* @param name
* @param value
* @param maxAge
*/
public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
if (maxAge > 0) {
cookie.setMaxAge(maxAge);
}
response.addCookie(cookie);
}
/**
* 删除cookie
*
* @param response
* @param name
*/
public static void removeCookie(HttpServletResponse response, String name) {
Cookie uid = new Cookie(name, null);
uid.setPath("/");
uid.setMaxAge(0);
response.addCookie(uid);
}
/**
* 获取cookie值
*
* @param request
* @return
*/
public static String getUid(HttpServletRequest request,String cookieName) {
Cookie cookies[] = request.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals(cookieName)) {
return cookie.getValue();
}
}
return null;
}
}
package com.id0304.utils;
import org.apache.commons.lang.time.DateFormatUtils;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss",
"yyyy.MM.dd HH:mm", "yyyy.MM" };
/**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public static String getDate() {
return getDate("yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
if (date == null) {
return null;
}
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
*/
public static String formatDateTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 日期型字符串转化为日期 格式
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
* "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取过去的天数
*
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime() - date.getTime();
return t / (24 * 60 * 60 * 1000);
}
/**
* 获得当前时间的字符串类型
* @return
*/
public static String toStr() {
return toStr(new Date());
}
/**
* Date转成"yyyy-MM-dd HH:mm:ss"格式的字符串
* @param date
* @return
*/
public static String toStr(Date date) {
return format(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 将一个 Date 格式化为日期/时间字符串
* @param date 要格式化为时间字符串的时间值
* @param pattern 日期和时间格式的模式
* @return 已格式化的时间字符串
*/
public static String format(Date date, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}
/**
* 获取过去的小时
*
* @param date
* @return
*/
public static long pastHour(Date date) {
long t = new Date().getTime() - date.getTime();
return t / (60 * 60 * 1000);
}
/**
* 获取过去的分钟
*
* @param date
* @return
*/
public static long pastMinutes(Date date) {
long t = new Date().getTime() - date.getTime();
return t / (60 * 1000);
}
/**
* 将毫秒值转换为时间(天,时:分:秒.毫秒)
*
* @param timeMillis
* @return
*/
public static String formatDateTime(long timeMillis) {
long day = timeMillis / (24 * 60 * 60 * 1000);
long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public static double getDaysBetweenDate(Date before, Date after) {
return getMillisecBetweenDate(before,after) / (1000 * 60 * 60 * 24);
}
/**
* 获取两个日期之间的毫秒数
* @param before
* @param after
* @return
*/
public static long getMillisecBetweenDate(Date before, Date after){
long beforeTime = before.getTime();
long afterTime = after.getTime();
return afterTime - beforeTime;
}
/**
* 获取当前月的第一天
* @return
*/
public static String getFirstDayOfMonth() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//获取当前月第一天:
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 0);
c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
String first = format.format(c.getTime());
return first;
}
/**
* 获得当前时间的时间戳
* @return
*/
public static Timestamp getTimestamp() {
return new Timestamp(new Date().getTime());
}
/**
*
* 方法名: getDoubleType
* 描述: 返回时间的 double
* 参数: @param dateString
* 参数: @return
* 参数: @throws ParseException 设定文件
*/
public static double getDoubleType(String dateString) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateString);
return date.getTime();
}
/**
* 获得两个Date之间的秒数
* @param startTime 开始时间
* @param endTime 结束时间
* @return
*/
public static int calLastedTime(Date startTime, Date endTime) {
long a = startTime.getTime();
long b = endTime.getTime();
int c = (int) ((a - b) / 1000);
return c;
}
/**
* 获取若干个小时之后的时间(字符串类型)
* @param startTime
* @param hours
* @return
*/
public static String getPassHours(String startTime, int hours) {
// 获取一个小时以后的时间
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date = null;
try {
date = df.parse(startTime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + hours);
return df.format(calendar.getTime());
}
/**
* "yyyy-MM-dd HH:mm:ss"格式的日期在若干天数后的时间(字符串)
* @param time
* @param days
* @return
*/
public static String getAddDate(String time,int days) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = dateFormat.parse(time);
} catch (ParseException e) {
e.printStackTrace();
} // 指定日期
Date newDate = null;
try {
newDate = addDate(date, days);
} catch (ParseException e) {
e.printStackTrace();
} // 指定日期加上20天
String st = dateFormat.format(newDate);
return st;
}
/**
* 指定时间在若干天后的时间
* @param date
* @param day
* @return
* @throws ParseException
*/
public static Date addDate(Date date,long day) throws ParseException {
long time = date.getTime(); // 得到指定日期的毫秒数
day = day*24*60*60*1000; // 要加上的天数转换成毫秒数
time+=day; // 相加得到新的毫秒数
return new Date(time); // 将毫秒数转换成日期
}
/**
* 获取当天的某一时刻Date
* @param hour 24小时
* @param min 分钟
* @param sec 秒
* @param mill 毫秒
* @return
*/
public static Date getMoment(int hour, int min, int sec, int mill){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY,hour);
calendar.set(Calendar.MINUTE,min);
calendar.set(Calendar.SECOND,sec);
calendar.set(Calendar.MILLISECOND,mill);
return calendar.getTime();
}
/**
* 获得指定某年某月某日某刻的Date
* @param year 年
* @param month 月
* @param day 日
* @param hour 24小时制
* @param min 分钟
* @param sec 秒
* @param mill 毫秒
* @return
*/
public static Date getMoment(int year,int month,int day,int hour,int min,int sec,int mill){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH,day);
calendar.set(Calendar.HOUR_OF_DAY,hour);
calendar.set(Calendar.MINUTE,min);
calendar.set(Calendar.SECOND,sec);
calendar.set(Calendar.MILLISECOND,mill);
return calendar.getTime();
}
}
package com.id0304.utils;
import java.lang.reflect.Field;
import java.sql.Timestamp;
/**
* 反射工具类
*/
public class ReflectionUtils {
//封装当前类和父类的所有属性,拼接属性sql
public static String fatherAndSonField(Object obj) {
if (obj == null) {
return null;
}
//获取class文件
Class classInfo = obj.getClass();
//获取当前类的属性sql
Field[] sonFields = classInfo.getDeclaredFields();
String s1 = getField(sonFields);
Field[] fatherFields = classInfo.getSuperclass().getDeclaredFields();
String s2 = getField(fatherFields);
return s1 + "," + s2;
}
//获取当前类和父类的属性值
public static String fatherAndSonFieldValue(Object obj) {
if (obj == null) {
return null;
}
//获取class文件
Class classInfo = obj.getClass();
//获取当前类的属性sql
Field[] sonFields = classInfo.getDeclaredFields();
String s1 = getFieldValue(obj, sonFields);
Field[] fatherFields = classInfo.getSuperclass().getDeclaredFields();
String s2 = getFieldValue(obj, fatherFields);
return s1 + "," + s2;
}
public static String getField(Field[] declaredFields) {
StringBuffer sf = new StringBuffer();
for (int i = 0; i < declaredFields.length; ++i) {
sf.append(declaredFields[i].getName());
if (i < declaredFields.length - 1) {
sf.append(",");
}
}
return sf.toString();
}
public static String getFieldValue(Object obj, Field[] declaredFields) {
StringBuffer sf = new StringBuffer();
for (int i = 0; i < declaredFields.length; ++i) {
//获取属性值
try {
//运行操作私有属性
declaredFields[i].setAccessible(true);
Field field = declaredFields[i];
Object value = field.get(obj);
//标识类型是否为String类型
boolean flag = false;
if (value != null && (value instanceof String||value instanceof Timestamp)) {
flag = true;
}
if (flag) {
sf.append("'" + value + "'");
} else {
sf.append(value);
}
if (i < declaredFields.length - 1) {
sf.append(",");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return sf.toString();
}
}
package com.id0304.utils;
import org.springframework.stereotype.Component;
import java.util.UUID;
public class TokenUtils {
public static String getToken(){
return UUID.randomUUID().toString();
}
}
package com.id0304.common.api;
import com.id0304.constants.BaseApiConstants;
import java.util.HashMap;
import java.util.Map;
/**
* 通用base api父类
*/
public class BaseApiService {
/**
* 返回错误
* @param msg
* @return
*/
public Map setResultError(String msg){
return setResult(BaseApiConstants.HTTP_500_CODE,BaseApiConstants.HTTP_ERROR_NAME,null);
}
/**
* 返回错误
* @param msg
* @return
*/
public Map setParamError(String msg){
return setResult(BaseApiConstants.HTTP_400_CODE,msg,null);
}
/**
* 返回成功
* @return
*/
public Map setResultSuccess(){
return setResult(BaseApiConstants.HTTP_200_CODE,BaseApiConstants.HTTP_SUCCESS_NAME,null);
}
/**
* 返回成功
* @return
*/
public Map setResultSuccessData(Object data){
return setResult(BaseApiConstants.HTTP_200_CODE,BaseApiConstants.HTTP_SUCCESS_NAME,data);
}
/**
* 返回成功
* @param msg
* @return
*/
public Map setResultSuccess(String msg){
return setResult(BaseApiConstants.HTTP_200_CODE,msg,null);
}
/**
* 自定义返回
* @param code
* @param msg
* @param data
* @return
*/
public Map setResult(Integer code,String msg,Object data){
HashMap result = new HashMap<>();
result.put(BaseApiConstants.HTTP_CODE_NAME,code);
result.put(BaseApiConstants.HTTP_MESSAGE_NAME,msg);
result.put(BaseApiConstants.HTTP_DATA_NAME,data);
return result;
}
}
package com.id0304.constants;
public interface BaseApiConstants {
String HTTP_MESSAGE_NAME = "msg";
String HTTP_CODE_NAME = "code";
String HTTP_DATA_NAME = "data";
Integer HTTP_200_CODE = 200;
Integer HTTP_500_CODE = 500;
Integer HTTP_400_CODE = 400;
String HTTP_ERROR_NAME = "error";
String HTTP_SUCCESS_NAME = "success";
}
package com.id0304.common.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.sql.Timestamp;
/**
* 封装一些相同的属性和字段
*/
@Setter
@Getter
public class BaseEntity {
//主键
private Long id;
//创建时间
private Timestamp created;
//修改时间
private Timestamp updated;
}
package com.id0304.common.log;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
//@Aspect
//@Component
@Slf4j
public class LogAspectServiceApi {
private JSONObject jsonObject = new JSONObject();
//申明一个切点 里面是execution表达式
@Pointcut("execution(public * com.id0304.api.service.*.*(..))")
private void controllerAspect(){
}
//请求method前打印的内容
@Before(value = "controllerAspect()")
public void methodBefore(JoinPoint joinPoint){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
log.info("==============请求内容==============");
try{
//打印请求内容
log.info("请求地址:"+request.getRequestURL().toString());
log.info("请求方式:"+request.getMethod());
log.info("请求类方法:"+joinPoint.getSignature());
log.info("请求类方法参数:"+ Arrays.toString(joinPoint.getArgs()));
}catch (Exception e){
//打印请求内容
log.error("###LogAspectServiceApi.class methodBefore() ### ERROR:",e);
}
log.info("==============请求内容==============");
}
// 在方法执行完结后打印返回内容
@AfterReturning(returning = "o",pointcut = "controllerAspect()")
public void methodAfterReturning(Object o){
log.info("--------------返回内容--------------");
try {
log.info("Response内容:"+jsonObject.toJSONString(o));
}catch (Exception e){
log.error("###LogAspectServiceApi.class methodBefore() ### ERROR:",e);
}
log.info("--------------返回内容--------------");
}
}
插入和删除语句公共提取,可以给其它Dao继承,利用反射拼接sql语句:
package com.id0304.common.mybatis;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Param;
public interface BaseDao {
//自定义sql语句,插入示例
@InsertProvider(type = BaseProvider.class,method = "save")
public void save(@Param("obj") Object obj,@Param("table") String table);
}
package com.id0304.common.mybatis;
import com.id0304.utils.ReflectionUtils;
import org.apache.ibatis.jdbc.SQL;
import java.util.Map;
public class BaseProvider {
//自定义封装sql语句
public String save(Map map){
//实体类
Object obj = map.get("obj");
//表名称
String table = (String) map.get("table");
//生成添加的sql语句,使用反射机制
//步骤:使用反射机制加载所有属性
SQL sql = new SQL() {
{
INSERT_INTO(table);
VALUES(ReflectionUtils.fatherAndSonField(obj), ReflectionUtils.fatherAndSonFieldValue(obj));
}
};
return sql.toString();
}
}
package com.id0304.common.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class BaseRedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 添加redis信息
* @param key
*/
public void setString(String key, String value) {
set(key, value, null);
}
public void setString(String key, String value, Long timeOut) {
set(key, value, timeOut);
}
private void set(String key, Object value, Long timeOut) {
if (value != null) {
if (value instanceof String) {
String setValue = (String) value;
stringRedisTemplate.opsForValue().set(key, setValue);
}
//设置有效期
if (timeOut != null) {
stringRedisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
}
}
}
/**
* 使用key查找redis信息
* @param key
*/
public String get(String key){
return stringRedisTemplate.opsForValue().get(key);
}
/**
* 使用key删除redis信息
* @param key
*/
public void delete(String key){
stringRedisTemplate.delete(key);
}
}