java项目常用的工具类

前言

在开发过程中,我们会遇到很多繁琐或者棘手的问题,但是,这些问题往往会存在一些便捷的工具类,来简化我们的开发,下面是我工作中经常使用到的工具类

常用工具类

日期工具类
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;/*** 日期工具类*/
public class DateUtils {/*** 获取今天* @return String* */public static String getToday(){return new SimpleDateFormat("yyyy-MM-dd").format(new Date());}/*** 获取昨天* @return String* */public static String getYestoday(){Calendar cal=Calendar.getInstance();cal.add(Calendar.DATE,-1);Date time=cal.getTime();return new SimpleDateFormat("yyyy-MM-dd").format(time);}/*** 获取本月开始日期* @return String* **/public static String getMonthStart(){Calendar cal=Calendar.getInstance();cal.add(Calendar.MONTH, 0);cal.set(Calendar.DAY_OF_MONTH, 1);Date time=cal.getTime();return new SimpleDateFormat("yyyy-MM-dd").format(time);}public static String getNowToString(){String today = DateUtils.getToday();String[] split = today.split("-");today=split[0]+split[1]+split[2];return today;}/*** 获取本月最后一天* @return String* **/public static String getMonthEnd(){Calendar cal=Calendar.getInstance();cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));Date time=cal.getTime();return new SimpleDateFormat("yyyy-MM-dd").format(time);}/*** 获取本周的第一天* @return String* **/public static String getWeekStart(){Calendar cal=Calendar.getInstance();cal.add(Calendar.WEEK_OF_MONTH, 0);cal.set(Calendar.DAY_OF_WEEK, 2);Date time=cal.getTime();return new SimpleDateFormat("yyyy-MM-dd").format(time);}/*** 获取本周的最后一天* @return String* **/public static String getWeekEnd(){Calendar cal=Calendar.getInstance();cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK));cal.add(Calendar.DAY_OF_WEEK, 1);Date time=cal.getTime();return new SimpleDateFormat("yyyy-MM-dd").format(time);}/*** 获取本年的第一天* @return String* **/public static String getYearStart(){return new SimpleDateFormat("yyyy").format(new Date())+"-01-01";}/*** 获取本年的最后一天* @return String* **/public static String getYearEnd(){Calendar calendar = Calendar.getInstance();calendar.set(Calendar.MONTH,calendar.getActualMaximum(Calendar.MONTH));calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));Date currYearLast = calendar.getTime();return new SimpleDateFormat("yyyy-MM-dd").format(currYearLast);}
}
easypoi导出excel
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;/*** @description: easypoi使用util工具类* @author: shilf3* @date: 2021/1/6 8:41*/
public class EasyPoiUtil {/*** @description: 导出excel* @author: shilf3* @date: 2021/1/6 8:41* @param: [list, title, sheetName, pojoClass, fileName, isCreateHeader, response]* @return: void*/public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws Exception {ExportParams exportParams = new ExportParams(title, sheetName);exportParams.setCreateHeadRows(isCreateHeader);defaultExport(list, pojoClass, fileName, response, exportParams);}/*** @description: 导出excel* @author: shilf3* @date: 2021/1/6 8:41* @param: [list, title, sheetName, pojoClass, fileName, response]* @return: void*/public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws Exception {defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));}/*** @description: 导出excel* @author: shilf3* @date: 2021/1/6 8:41* @param: [list, fileName, response]* @return: void*/public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws Exception {defaultExport(list, fileName, response);}private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws Exception {Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);if (workbook != null){downLoadExcel(fileName, response, workbook);}}}
poi工具类
import com.cnooc.lpg.stock.params.StockInventoryParam;
import com.cnooc.lpg.stock.vo.InventoryStatisticsVO;
import com.cnooc.lpg.stock.vo.StockInventoryFinishedVO2;
import com.cnooc.lpg.stock.vo.StockInventoryFinishedVo;
import com.cnooc.lpg.stock.vo.StockInventoryListByInventoryIdVo;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;/*** @Description:* @Author: zhangyk24* @Date: 2021/3/2**/
public class PoiUtil {/*** 创建标题样式* @param wb* @return*/public static HSSFCellStyle createTitleCellStyle(HSSFWorkbook wb) {HSSFCellStyle cellStyle = wb.createCellStyle();cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐cellStyle.setBorderBottom(BorderStyle.THIN); //下边框cellStyle.setBorderLeft(BorderStyle.THIN); //左边框cellStyle.setBorderRight(BorderStyle.THIN); //右边框cellStyle.setBorderTop(BorderStyle.THIN); //上边框
//        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());//背景颜色HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式headerFont1.setBold(false); //字体加粗headerFont1.setFontName("宋体"); // 设置字体类型headerFont1.setFontHeightInPoints((short) 16); // 设置字体大小
//        cellStyle.setFont(headerFont1); // 为标题样式设置字体样式return cellStyle;}/*** 创建表头样式* @param wb* @return*/public static HSSFCellStyle createHeadCellStyle(HSSFWorkbook wb) {HSSFCellStyle cellStyle = wb.createCellStyle();cellStyle.setWrapText(false);// 设置自动换行
//        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());//背景颜色cellStyle.setAlignment(HorizontalAlignment.CENTER); //水平居中cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //垂直对齐
//        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);cellStyle.setBorderBottom(BorderStyle.THIN); //下边框cellStyle.setBorderLeft(BorderStyle.THIN); //左边框cellStyle.setBorderRight(BorderStyle.THIN); //右边框cellStyle.setBorderTop(BorderStyle.THIN); //上边框HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式headerFont.setBold(false); //字体加粗headerFont.setFontName("宋体"); // 设置字体类型headerFont.setFontHeightInPoints((short) 16); // 设置字体大小
//        cellStyle.setFont(headerFont); // 为标题样式设置字体样式return cellStyle;}/*** @description: TODO* @param: wb* @return: org.apache.poi.hssf.usermodel.HSSFCellStyle* @author ex_zhangyk3* @date: 2021/6/23 10:43*/public static HSSFCellStyle createNoBorder(HSSFWorkbook wb) {HSSFCellStyle cellStyle = wb.createCellStyle();cellStyle.setWrapText(false);// 设置自动换行
//        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());//背景颜色cellStyle.setAlignment(HorizontalAlignment.CENTER); //水平居中cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //垂直对齐cellStyle.setWrapText(true);
//        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
//        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
//        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
//        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
//        cellStyle.setBorderTop(BorderStyle.THIN); //上边框HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式headerFont.setBold(false); //字体加粗headerFont.setFontName("宋体"); // 设置字体类型headerFont.setFontHeightInPoints((short) 16); // 设置字体大小
//        cellStyle.setFont(headerFont); // 为标题样式设置字体样式return cellStyle;}/*** @description: TODO* @param: wb* @return: org.apache.poi.hssf.usermodel.HSSFCellStyle* @author ex_zhangyk3* @date: 2021/6/23 10:43*/public static HSSFCellStyle createNoBorderNoCenter(HSSFWorkbook wb) {HSSFCellStyle cellStyle = wb.createCellStyle();cellStyle.setWrapText(false);// 设置自动换行
//        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());//背景颜色
//        cellStyle.setAlignment(HorizontalAlignment.CENTER); //水平居中
//        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //垂直对齐cellStyle.setWrapText(true);
//        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
//        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
//        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
//        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
//        cellStyle.setBorderTop(BorderStyle.THIN); //上边框HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式headerFont.setBold(false); //字体加粗headerFont.setFontName("宋体"); // 设置字体类型headerFont.setFontHeightInPoints((short) 16); // 设置字体大小
//        cellStyle.setFont(headerFont); // 为标题样式设置字体样式return cellStyle;}/*** 创建内容样式* @param wb* @return*/public static HSSFCellStyle createContentCellStyle(HSSFWorkbook wb) {HSSFCellStyle cellStyle = wb.createCellStyle();cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中cellStyle.setWrapText(false);// 设置自动换行cellStyle.setBorderBottom(BorderStyle.THIN); //下边框cellStyle.setBorderLeft(BorderStyle.THIN); //左边框cellStyle.setBorderRight(BorderStyle.THIN); //右边框cellStyle.setBorderTop(BorderStyle.THIN); //上边框// 生成12号字体HSSFFont font = wb.createFont();font.setBold(false);font.setFontName("宋体");// 设置字体类型
//        font.setColor((short)10);font.setFontHeightInPoints((short) 10);
//        cellStyle.setFont(font);return cellStyle;}public static void exportExcel(String fileName,HttpServletResponse httpServletResponse,HSSFWorkbook wb){try {httpServletResponse.setCharacterEncoding("UTF-8");httpServletResponse.setHeader("content-Type", "multipart/form-data");httpServletResponse.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));OutputStream stream = httpServletResponse.getOutputStream();if (null != wb && null != stream) {wb.write(stream);// 将数据写出去wb.close();stream.close();}} catch (Exception e) {e.printStackTrace();}}
}
redis操作类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;/*** @description: redis操作* @date: 2021/3/17 8:47*/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{@Autowiredpublic RedisTemplate redisTemplate;/*** 缓存基本的对象,Integer、String、实体类等** @param key 缓存的键值* @param value 缓存的值*/public <T> void setCacheObject(final String key, final T value){redisTemplate.opsForValue().set(key, value);}/*** 缓存基本的对象,Integer、String、实体类等** @param key 缓存的键值* @param value 缓存的值* @param timeout 时间* @param timeUnit 时间颗粒度*/public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit){redisTemplate.opsForValue().set(key, value, timeout, timeUnit);}/*** 设置有效时间** @param key Redis键* @param timeout 超时时间* @return true=设置成功;false=设置失败*/public boolean expire(final String key, final long timeout){return expire(key, timeout, TimeUnit.SECONDS);}/*** 设置有效时间** @param key Redis键* @param timeout 超时时间* @param unit 时间单位* @return true=设置成功;false=设置失败*/public boolean expire(final String key, final long timeout, final TimeUnit unit){return redisTemplate.expire(key, timeout, unit);}/*** 获得缓存的基本对象。** @param key 缓存键值* @return 缓存键值对应的数据*/public <T> T getCacheObject(final String key){ValueOperations<String, T> operation = redisTemplate.opsForValue();return operation.get(key);}/*** 删除单个对象** @param key*/public boolean deleteObject(final String key){return redisTemplate.delete(key);}/*** 删除集合对象** @param collection 多个对象* @return*/public long deleteObject(final Collection collection){return redisTemplate.delete(collection);}/*** 缓存List数据** @param key 缓存的键值* @param dataList 待缓存的List数据* @return 缓存的对象*/public <T> long setCacheList(final String key, final List<T> dataList){Long count = redisTemplate.opsForList().rightPushAll(key, dataList);return count == null ? 0 : count;}/*** 获得缓存的list对象** @param key 缓存的键值* @return 缓存键值对应的数据*/public <T> List<T> getCacheList(final String key){return redisTemplate.opsForList().range(key, 0, -1);}/*** 缓存Set** @param key 缓存键值* @param dataSet 缓存的数据* @return 缓存数据的对象*/public <T> long setCacheSet(final String key, final Set<T> dataSet){Long count = redisTemplate.opsForSet().add(key, dataSet);return count == null ? 0 : count;}/*** 获得缓存的set** @param key* @return*/public <T> Set<T> getCacheSet(final String key){return redisTemplate.opsForSet().members(key);}/*** 缓存Map** @param key* @param dataMap*/public <T> void setCacheMap(final String key, final Map<String, T> dataMap){if (dataMap != null) {redisTemplate.opsForHash().putAll(key, dataMap);}}/*** 获得缓存的Map** @param key* @return*/public <T> Map<String, T> getCacheMap(final String key){return redisTemplate.opsForHash().entries(key);}/*** 往Hash中存入数据** @param key Redis键* @param hKey Hash键* @param value 值*/public <T> void setCacheMapValue(final String key, final String hKey, final T value){redisTemplate.opsForHash().put(key, hKey, value);}/*** 获取Hash中的数据** @param key Redis键* @param hKey Hash键* @return Hash中的对象*/public <T> T getCacheMapValue(final String key, final String hKey){HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();return opsForHash.get(key, hKey);}/*** 获取多个Hash中的数据** @param key Redis键* @param hKeys Hash键集合* @return Hash对象集合*/public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys){return redisTemplate.opsForHash().multiGet(key, hKeys);}/*** 获得缓存的基本对象列表** @param pattern 字符串前缀* @return 对象列表*/public Collection<String> keys(final String pattern){return redisTemplate.keys(pattern);}
}
分页结果封装类
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;import java.util.List;/*** @description: 分页查询结果封装类* @date: 2021/1/6 14:00*/
@Getter
@Setter
public class PageFormat {@ApiModelProperty(value = "数据总条数")private long total;@ApiModelProperty(value = "数据集合")private List<?> rows;//构造器,返回分页结果类public PageFormat(List<?> list) {PageInfo<?> info = new PageInfo<>(list);this.total = info.getTotal();this.rows = info.getList();}
}
正则表达式校验
import java.util.regex.Pattern;/*** @description: 校验工具* @date: 2021/3/4 16:01* @param:* @return:*/
public class ValidatorUtil {/*** 正则表达式:验证用户名*/public static final String REGEX_USERNAME = "^[a-zA-Z]\\w{5,20}$";/*** 正则表达式:验证密码*/public static final String REGEX_PASSWORD = "^[a-zA-Z0-9]{6,20}$";/*** 正则表达式:验证手机号*/public static final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";/*** 正则表达式:验证邮箱*/public static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";/*** 正则表达式:验证汉字*/public static final String REGEX_CHINESE = "^[\u4e00-\u9fa5],{0,}$";/*** 正则表达式:验证身份证*/public static final String REGEX_ID_CARD = "(^\\d{18}$)|(^\\d{15}$)";/*** 正则表达式:验证URL*/public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";/*** 正则表达式:验证IP地址*/public static final String REGEX_IP_ADDR = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";/*** 校验用户名** @param username* @return 校验通过返回true,否则返回false*/public static boolean isUsername(String username) {return Pattern.matches(REGEX_USERNAME, username);}/*** 校验密码** @param password* @return 校验通过返回true,否则返回false*/public static boolean isPassword(String password) {return Pattern.matches(REGEX_PASSWORD, password);}/*** 校验手机号** @param mobile* @return 校验通过返回true,否则返回false*/public static boolean isMobile(String mobile) {return Pattern.matches(REGEX_MOBILE, mobile);}/*** 校验邮箱** @param email* @return 校验通过返回true,否则返回false*/public static boolean isEmail(String email) {return Pattern.matches(REGEX_EMAIL, email);}/*** 校验汉字** @param chinese* @return 校验通过返回true,否则返回false*/public static boolean isChinese(String chinese) {return Pattern.matches(REGEX_CHINESE, chinese);}/*** 校验身份证** @param idCard* @return 校验通过返回true,否则返回false*/public static boolean isIDCard(String idCard) {return Pattern.matches(REGEX_ID_CARD, idCard);}/*** 校验URL** @param url* @return 校验通过返回true,否则返回false*/public static boolean isUrl(String url) {return Pattern.matches(REGEX_URL, url);}/*** 校验IP地址** @param ipAddr* @return*/public static boolean isIPAddr(String ipAddr) {return Pattern.matches(REGEX_IP_ADDR, ipAddr);}}
解密微信用户信息密文
import org.apache.commons.codec.binary.Base64;import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;/*** @description: 解密微信用户信息密文* @date: 2021/3/25 16:51*/
public class DecryptUtil {// 算法名public static final String KEY_NAME = "AES";// ECB模式只用密钥即可对数据进行加密解密,CBC模式需要添加一个ivpublic static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";/*** @param encrypted   目标密文* @param session_key 会话ID* @param iv          加密算法的初始向量*/public static String wxDecrypt(String encrypted, String session_key, String iv) {String json = null;byte[] encrypted64 = Base64.decodeBase64(encrypted);byte[] key64 = Base64.decodeBase64(session_key);byte[] iv64 = Base64.decodeBase64(iv);byte[] data;try {init();json = new String(decrypt(encrypted64, key64, generateIV(iv64)));} catch (Exception e) {e.printStackTrace();}return json;}/*** 初始化密钥*/public static void init() throws Exception {Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());KeyGenerator.getInstance(KEY_NAME).init(128);}/*** 生成iv*/public static AlgorithmParameters generateIV(byte[] iv) throws Exception {// iv 为一个 16 字节的数组,这里采用和 iOS 端一样的构造方法,数据全为0// Arrays.fill(iv, (byte) 0x00);AlgorithmParameters params = AlgorithmParameters.getInstance(KEY_NAME);params.init(new IvParameterSpec(iv));return params;}/*** 生成解密*/public static byte[] decrypt(byte[] encryptedData, byte[] keyBytes, AlgorithmParameters iv)throws Exception {Key key = new SecretKeySpec(keyBytes, KEY_NAME);Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);// 设置为解密模式cipher.init(Cipher.DECRYPT_MODE, key, iv);return cipher.doFinal(encryptedData);}}
RSA加解密工具类
import com.cnooc.lpg.login.constant.CodeContent;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;/*** 类描述:RSA加解密工具类*/
@Slf4j
public class RsaUtil {private static final int DEFAULT_RSA_KEY_SIZE = 2048;private static final String KEY_ALGORITHM = "RSA";//    public static void main(String[] args){Map<String,String> result = generateRsaKey(DEFAULT_RSA_KEY_SIZE);System.out.println("公钥为:" + result.get("publicKey") );System.out.println("私钥为:" + result.get("privateKey"));
//        //{"password":"","username":"sysadmin"}
//    	String decrypt = decrypt(
//                "OFi5AYFCSwEPoycUetN9nqQAFffIGz5RDRqMqKQf7cvn2TU7tlyxJlfhrQ97asuns1B1nQf/NCRYLePFRZ32+k7g7JGx3IxteHW8uQEcyMZXOOnzWoM4mPkm6t2RmsQkniTQZCe0ag8ygacpG+8cmjPkzS/+gdh7eXtimytKz9jCu3dSgdjzfhvRqrzu0FXb3Ff7MQYRBB7g+/Ixa3eZ5wJyDWjURA0F6ESl/P6LMtuLY9cOabGMNe24BDPgZKwGRGaSUyW4FPrMycQQY+gfSuru1fSdm61JI/PgBoQLbdz7XRSSttfHmmKhaIzbBjDr/Gjj0D75Ax14u3xZyk+yHw==",
//                "");
//    	System.out.println(decrypt);
//    }/*** 生成RSA 公私钥,可选长度为1025,2048位.*/public static Map<String, String> generateRsaKey(int keySize) {Map<String, String> result = new HashMap<>(2);try {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);// 初始化密钥对生成器,密钥大小为1024 2048位keyPairGen.initialize(keySize, new SecureRandom());// 生成一个密钥对,保存在keyPair中KeyPair keyPair = keyPairGen.generateKeyPair();// 得到公钥字符串result.put("publicKey", new String(Base64.encodeBase64(keyPair.getPublic().getEncoded())));// 得到私钥字符串result.put("privateKey", new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded())));} catch (GeneralSecurityException e) {e.printStackTrace();}return result;}/*** RSA私钥解密** @param str        加密字符串* @param privateKey 私钥* @return 铭文* @throws Exception 解密过程中的异常信息*/public static String decrypt(String str, String privateKey) {//64位解码加密后的字符串byte[] inputByte;String outStr = "";try {inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));//base64编码的私钥byte[] decoded = Base64.decodeBase64(privateKey);RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));//RSA解密Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, priKey);outStr = new String(cipher.doFinal(inputByte));} catch (UnsupportedEncodingException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException | NoSuchAlgorithmException e) {log.info("<<<<<<传入的的密码是明文不需要解密",e);// e.printStackTrace();}return outStr;}/*** 加密** @param str       明文* @param publicKey 公钥* @return*/public static String encrypt(String str, String publicKey) throws UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException {// 从字符串加载公钥byte[] publicKeyByte = Base64.decodeBase64(publicKey);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyByte);RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);Cipher cipher = null;cipher=Cipher.getInstance(KEY_ALGORITHM);//默认RSA算法cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);//rsa 加密后的二级制数据byte[] reaByte = cipher.doFinal(str.getBytes("UTF-8"));//base64 加密byte[] base64Byte = Base64.encodeBase64(reaByte);String encryptCode = new String(base64Byte, "UTF-8");return encryptCode;}public static void main(String[] args) throws UnsupportedEncodingException, IllegalBlockSizeException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, BadPaddingException, NoSuchPaddingException {
//        Map<String, String> result = generateRsaKey(DEFAULT_RSA_KEY_SIZE);
//        System.out.println("公钥为:" + result.get("publicKey"));
//        System.out.println("私钥为:" + result.get("privateKey"));//{"password":"","username":"sysadmin"}
//        String key = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCbvhNPSsTpEMvukZjVR2ppXguMueOpt3cyTjuDKrFYc0MuuwkA43dRSuo4MN1D+eGpQbZCLVcwoj2xWiHyrH4BSImSpRbGP/lQZ2ypaMdDi6OE8FeGPjrmVOuu0SOpAdP7NGNs0kdmo3GMON7GmfkslQ4uAAH87QLh8RdLR1zOBD34zK7+oVSQpDOcOoTk6Dez0x7tOsKX46DGB5vAdWNxEmntNKn95hQggtpFppm306jSsvLVfbZMDVOE9tYgTmKQhGh9M7TKkCgLSLuEjkrLpWNRZ+VAtJewQwQ0D0fLpMVtwduLwZyg23NikDt/jG5hAqmZvcoF9UVlR7jVOJrRAgMBAAECggEBAIzaF86jeXirlzQ4+3cQcp2+z0VDrTGF2shlVo9nIiMzgzQVNaxXDEc6MKAHGWXr7XnNE0/Af9VdNdxa/s7hz8fLWZiFtBYyL4HXN7/zIhvlg0qsrwua5lv/u3NMdCram2PaWn1FpAugkAXYPSpygJcga0WQ/jtIA05iY8XSUY2Df/ClO7ua3wrZJ+kwcg9TVT9FlNWKg59/BMDY/IllWmHldhpshT282JwOjZkh+Ggu5+9ryRCHTBaeJnig9dvnTYC30XoLF5vFWc7pUE+ZyPNMjuNY8R0/Rsm88tnE6SEWlCP3gesYf0uEk7dlPlsHQGAWj3TAeAOYzw7aUxL0ZAECgYEA2usIf4k/eVDJOKu4khrscDRDm06IJYzBZ9R/UIw4erA1tcQ/PiEUglYwqOCKwU8lkTJ9vJa8RM8ZngzwGjoVdwHDv6Y4gHBPD21vLiJS0v0XJLgtAAFP/KK3DnFBBJTA0+mSuedTR1TAYM6ARFei8sxeFd7oEoRjmlz6jfEMKxECgYEAth+NRSiaP6u2Ux840MkNnoQAXUG6BAiPnvdxLixmLxOb5R40pGChQQkjU9DJclsCM+ov92MkktqV739c17gxSVW1T/K0Edfa7J7j5C+ZOtvquI3n74oRviQ+taYX06AAmrHi8TRvDGliwr5RFPp58YNubg+r+kVr32zT7w1788ECgYABMG2nY7N4kTvGlwg1ovfN1DrZyR9sNMuIKNtYMKrN388q4ZoGWF+oJZe2EyIt0qQ9maydLaRwKz/UX/Wd7trW/qd1jw2XhQSo7MtB0OXqR32ssWNtMJSipq+f4HWd9MDnZclqQRtus8Mnw3dm56L29q08KS3Ri+6OlBq4UqriQQKBgQCMOPDRLbjNiwzfJOvevN3yjVmmc8Of9WN3FrcawO6QEn32Q3JumUOuyjVcBCYGGRIyHH5/7+Kp+wh0FNDL+rJf71ChVJHWJycVBiUafJdy3P30yLWqFdkhV9C8lTxFIS017f54jlFt8forTNMq3sti6znsHb7g+/BZXvYyWWR1QQKBgQC1m6jckUmF4iuPkOBB5bTCJPMWXxWaKroO92D5rc0V9Nv+jR2NbSk/C/8r2G6aZL6fCRFiRK2bV/qYeI0TF4vc9NreQRvbXXrSOY5DlpNnC+v/6EDiHrxXNxrKk8NOicJvStmUVBfpn8D60Rh5psjlzWZHTLXhYK7zdSEg+vpJIw==";
//        String decrypt = decrypt(
//                "OFi5AYFCSwEPoycUetN9nqQAFffIGz5RDRqMqKQf7cvn2TU7tlyxJlfhrQ97asuns1B1nQf/NCRYLePFRZ32+k7g7JGx3IxteHW8uQEcyMZXOOnzWoM4mPkm6t2RmsQkniTQZCe0ag8ygacpG+8cmjPkzS/+gdh7eXtimytKz9jCu3dSgdjzfhvRqrzu0FXb3Ff7MQYRBB7g+/Ixa3eZ5wJyDWjURA0F6ESl/P6LMtuLY9cOabGMNe24BDPgZKwGRGaSUyW4FPrMycQQY+gfSuru1fSdm61JI/PgBoQLbdz7XRSSttfHmmKhaIzbBjDr/Gjj0D75Ax14u3xZyk+yHw==",
//                key);String publickey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm74TT0rE6RDL7pGY1UdqaV4LjLnjqbd3Mk47gyqxWHNDLrsJAON3UUrqODDdQ/nhqUG2Qi1XMKI9sVoh8qx+AUiJkqUWxj/5UGdsqWjHQ4ujhPBXhj465lTrrtEjqQHT+zRjbNJHZqNxjDjexpn5LJUOLgAB/O0C4fEXS0dczgQ9+Myu/qFUkKQznDqE5Og3s9Me7TrCl+OgxgebwHVjcRJp7TSp/eYUIILaRaaZt9Oo0rLy1X22TA1ThPbWIE5ikIRofTO0ypAoC0i7hI5Ky6VjUWflQLSXsEMENA9Hy6TFbcHbi8GcoNtzYpA7f4xuYQKpmb3KBfVFZUe41Tia0QIDAQAB";//  System.out.println(decrypt);String s = encrypt(CodeContent.LPG_PASSWORD, publickey);System.out.println(s);
//        String decode= decrypt(s,key);
//        System.out.println(decode);
//         String pwd="password";
//       byte[] encodeByte=  Base64.encodeBase64(pwd.getBytes("UTF-8"));
//          String encodePWD=new String(encodeByte,"UTF-8");
//        System.out.println("====加密以后:"+encodePWD);
//        //解密
//        byte[] decodePWD= Base64.decodeBase64(encodePWD.getBytes("UTF-8"));
//        String pwd2=new String(decodePWD,"UTF-8");
//        System.out.println("====解密以后:"+pwd2);}}
AES128 算法
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;public class Aes {/**** @author ngh* AES128 算法** CBC 模式** PKCS7Padding 填充模式** CBC模式需要添加偏移量参数iv,必须16位* 密钥 sessionKey,必须16位** 介于java 不支持PKCS7Padding,只支持PKCS5Padding 但是PKCS7Padding 和 PKCS5Padding 没有什么区别* 要实现在java端用PKCS7Padding填充,需要用到bouncycastle组件来实现*/private final String sessionKey = "0102030405060708";// 偏移量 16位private final String iv = "0102030405060708";// 算法名称final String KEY_ALGORITHM = "AES";// 加解密算法/模式/填充方式final String algorithmStr = "AES/CBC/PKCS7Padding";// 加解密 密钥 16位byte[] ivByte;byte[] keybytes;private Key key;private Cipher cipher;boolean isInited = false;public void init() {// 如果密钥不足16位,那么就补足.  这个if 中的内容很重要keybytes = sessionKey.getBytes();ivByte = iv.getBytes();
//        int base = 16;
//        if (keybytes.length % base != 0) {
//            int groups = keybytes.length / base + (keybytes.length % base != 0 ? 1 : 0);
//            byte[] temp = new byte[groups * base];
//            Arrays.fill(temp, (byte) 0);
//            System.arraycopy(keybytes, 0, temp, 0, keybytes.length);
//            keybytes = temp;
//        }// 初始化Security.addProvider(new BouncyCastleProvider());// 转化成JAVA的密钥格式key = new SecretKeySpec(keybytes, KEY_ALGORITHM);try {// 初始化ciphercipher = Cipher.getInstance(algorithmStr, "BC");} catch (NoSuchAlgorithmException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchPaddingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchProviderException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** 加密方法** @param content*            要加密的字符串* @param keyBytes*            加密密钥* @return*/public String encrypt(String content) {byte[] encryptedText = null;byte[] contentByte = content.getBytes();init();try {cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivByte));encryptedText = cipher.doFinal(contentByte);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return new String(Hex.encode(encryptedText));}/*** 解密方法** @param encryptedData*            要解密的字符串* @param keyBytes*            解密密钥* @return*/public String decrypt(String encryptedData) {byte[] encryptedText = null;byte[] encryptedDataByte = Hex.decode(encryptedData);init();try {cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivByte));encryptedText = cipher.doFinal(encryptedDataByte);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return new String(encryptedText);}public static void main(String[] args) {Aes aes = new Aes();//加密字符串String content = "18435318060";System.out.println("加密前的:" + content);
//        System.out.println("加密密钥:" + new String(keybytes));// 加密方法String enc = aes.encrypt(content);System.out.println("加密后的内容:" + enc);// 解密方法String dec = aes.decrypt(enc);System.out.println("解密后的内容:" + dec);}
}
获取季度、复制集合
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;import java.lang.reflect.InvocationTargetException;
import java.util.*;public class BeanUtils {//获取上一个季度&年份public static Map<String,Integer> getLastQuarterAndYear(Date date){Date today = new Date();//获取当前年份当前季度int year = getYear(today);int quarter = getSeason(today);//获取上一季度&年份int lastQuarter;int lastQuarterYear;lastQuarter = quarter == 1 ? 4: quarter - 1;lastQuarterYear = quarter == 1 ? year - 1 : year;Map<String,Integer> resultMap = new HashMap<>();resultMap.put("year",lastQuarterYear);resultMap.put("quarter",lastQuarter);return resultMap;}/*** 取得日期:年** @param date* @return*/public static int getYear(Date date) {Calendar c = Calendar.getInstance();c.setTime(date);int year = c.get(Calendar.YEAR);return year;}/*** 取得日期 季度** @param date* @return 1 :第一季度 2 :第二季度 3: 第三季度 4: 第四季度*/public static int getSeason(Date date) {int season = 0;Calendar c = Calendar.getInstance();c.setTime(date);int month = c.get(Calendar.MONTH);switch (month) {case Calendar.JANUARY:case Calendar.FEBRUARY:case Calendar.MARCH:season = 1;break;case Calendar.APRIL:case Calendar.MAY:case Calendar.JUNE:season = 2;break;case Calendar.JULY:case Calendar.AUGUST:case Calendar.SEPTEMBER:season = 3;break;case Calendar.OCTOBER:case Calendar.NOVEMBER:case Calendar.DECEMBER:season = 4;break;default:break;}return season;}public static boolean isEmptyStr(String str) {return str == null || str.trim().length() == 0;}public static String[] getNullPropertyNames(Object source) {final BeanWrapper src = new BeanWrapperImpl(source);java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();Set<String> emptyNames = new HashSet<String>();for (java.beans.PropertyDescriptor pd : pds) {Object srcValue = src.getPropertyValue(pd.getName());if (srcValue == null)emptyNames.add(pd.getName());}String[] result = new String[emptyNames.size()];return emptyNames.toArray(result);}public static void copyPropertiesIgnoreNull(Object src, Object target) {org.springframework.beans.BeanUtils.copyProperties(src, target, getNullPropertyNames(src));}/*** 复制集合** @param <E>* @param source* @param destinationClass* @return* @throws InstantiationException* @throws InvocationTargetException* @throws IllegalAccessException*/public static <E> List<E> copyToPropertiesIgnoreNull(List<?> source, Class<E> destinationClass)throws IllegalAccessException, InvocationTargetException, InstantiationException {if (source.size() == 0)return Collections.emptyList();List<E> res = new ArrayList<E>(source.size());for (Object o : source) {E e = destinationClass.newInstance();copyPropertiesIgnoreNull(o, e);res.add(e);}return res;}public static <E> List<E> copyTo(List<?> source, Class<E> destinationClass)throws IllegalAccessException, InvocationTargetException, InstantiationException {if (source.size() == 0)return Collections.emptyList();List<E> res = new ArrayList<E>(source.size());for (Object o : source) {E e = destinationClass.newInstance();org.springframework.beans.BeanUtils.copyProperties(o, e);res.add(e);}return res;}}
Date操作工具类
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;/*** @description: Date操作工具类* @date: 2021/1/13 9:03*/
public class DateUtil {private DateUtil() {}public static final String yyyyMMdd = "yyyyMMdd";/*** 英文简写(默认)如:2010-12-01*/public static final String FORMAT_SHORT = "yyyy-MM-dd";/*** 英文全称 如:2010-12-01 23:15:06*/public static final String FORMAT_LONG = "yyyy-MM-dd HH:mm:ss";/*** 精确到毫秒的完整时间 如:yyyy-MM-dd HH:mm:ss.S*/public static final String FORMAT_FULL = "yyyy-MM-dd HH:mm:ss.S";/*** 英文简写(默认)如:2017-08*/public static final String FORMAT_YEAR_MONTH = "yyyy-MM";/*** 中文简写 如:2010年12月01日*/public static final String FORMAT_SHORT_CN = "yyyy年MM月dd";/*** 中文全称 如:2010年12月01日 23时15分06秒*/public static final String FORMAT_LONG_CN = "yyyy年MM月dd日  HH时mm分ss秒";/*** 精确到毫秒的完整中文时间*/public static final String FORMAT_FULL_CN = "yyyy年MM月dd日  HH时mm分ss秒SSS毫秒";public static final String yyyyMMddHHmmss = "yyyyMMddHHmmss";public static final String yyyyMMdd_HHmmss = "yyyyMMdd HHmmss";public static final String yyyyMMddHHmmssSSS = "yyyyMMddHHmmssSSS";/*** 获得默认的 date pattern*/public static final String getDatePattern() {return FORMAT_LONG;}/*** 使用预设格式格式化日期** @param date* @return*/public static final String format(Date date) {return format(date, getDatePattern());}/*** 使用用户格式格式化日期** @param date    日期* @param pattern 日期格式* @return*/public static final String format(LocalDateTime date, String pattern) {String returnValue = "";if (date != null) {DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);returnValue = df.format(date);}return (returnValue);}/*** 使用用户格式格式化日期** @param date    日期* @param pattern 日期格式* @return*/public static final String format(Date date, String pattern) {String returnValue = "";if (date != null) {SimpleDateFormat df = new SimpleDateFormat(pattern);returnValue = df.format(date);}return (returnValue);}public static final String format(String date) {String returnValue = "";if (StringUtils.isNotEmpty(date)) {returnValue = date.replace("-", "");}return returnValue;}/*** 使用预设格式提取字符串日期** @param strDate 日期字符串* @return*/public static final Date parse(String strDate) {return parse(strDate, getDatePattern());}/*** 使用用户格式提取字符串日期** @param strDate 日期字符串* @param pattern 日期格式* @return*/public static final Date parse(String strDate, String pattern) {SimpleDateFormat df = new SimpleDateFormat(pattern);try {return df.parse(strDate);} catch (ParseException e) {return null;}}public static final Date strToDate(String strDate) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");Date date = null;try {date = simpleDateFormat.parse(strDate);} catch (ParseException e) {e.printStackTrace();}return date;}/*** 在日期上增加数个整月** @param date 日期* @param n    要增加的月数* @return*/public static final Date addMonth(Date date, int n) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(Calendar.MONTH, n);return cal.getTime();}/*** 在日期上增加天数** @param date 日期* @param n    要增加的天数* @return*/public static final Date addDay(Date date, int n) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(Calendar.DATE, n);return cal.getTime();}/*** 在秒** @param date 日期* @param n    要增加秒* @return*/public static final Date addSecond(Date date, int n) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(Calendar.SECOND, n);return cal.getTime();}/*** 获取时间戳*/public static final String getTimeString() {SimpleDateFormat df = new SimpleDateFormat(FORMAT_FULL);Calendar calendar = Calendar.getInstance();return df.format(calendar.getTime());}/*** 获取日期年份** @param date 日期* @return*/public static final String getYear(Date date) {return format(date).substring(0, 4);}/*** 计算两个日期相差的天数** @param date1* @param date2* @return*/public static final int countDays(Date date1, Date date2) {Calendar c = Calendar.getInstance();c.setTime(date1);long t1 = c.getTimeInMillis();c.setTime(date2);long t2 = c.getTime().getTime();return (int) (t1 / 1000 - t2 / 1000) / 3600 / 24;}/*** 按默认格式的字符串距离今天的天数** @param date 日期字符串* @return*/public static final int countDays(String date) {long t = Calendar.getInstance().getTime().getTime();Calendar c = Calendar.getInstance();c.setTime(parse(date));long t1 = c.getTime().getTime();return (int) (t / 1000 - t1 / 1000) / 3600 / 24;}/*** 按用户格式字符串距离今天的天数** @param date   日期字符串* @param format 日期格式* @return*/public static final int countDays(String date, String format) {long t = Calendar.getInstance().getTime().getTime();Calendar c = Calendar.getInstance();c.setTime(parse(date, format));long t1 = c.getTime().getTime();return (int) (t / 1000 - t1 / 1000) / 3600 / 24;}public static final Date addMinute(Date date, int n) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(Calendar.MINUTE, n);return cal.getTime();}public static final Date addHour(Date date, int n) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(Calendar.HOUR, n);return cal.getTime();}public static final Date addYear(Date date, int n) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(Calendar.YEAR, n);return cal.getTime();}public static final boolean isBefore(Date date1, Date date2) {if (null == date1 || null == date2) return false;return date1.before(date2);}public static final boolean isAfter(Date date1, Date date2) {if (null == date1 || null == date2) return false;return date1.after(date2);}public static final boolean isBetween(Date date, Date start, Date end) {if (null == date || null == start || null == end) return false;return isAfter(date, start) && isBefore(date, end);}/*** 获取今天剩余的秒数*/public static final Integer todayRestTimeBySecond() {return (int) (86400 - DateUtils.getFragmentInSeconds(Calendar.getInstance(), Calendar.DATE));}/*** 获取一天开始时间** @return*/public static Date getDayStart(Date date) {return DateUtil.parse(DateUtil.format(date, DateUtil.yyyyMMdd) + "000000", DateUtil.yyyyMMddHHmmss);}/*** 获取一天结束时间** @return*/public static Date getDayEnd(Date date) {return DateUtil.parse(DateUtil.format(date, DateUtil.yyyyMMdd) + "235959", DateUtil.yyyyMMddHHmmss);}/*** 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致** @param nowTime   当前时间* @param startTime 开始时间* @param endTime   结束时间*/public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {if (nowTime.getTime() == startTime.getTime()|| nowTime.getTime() == endTime.getTime()) {return true;}Calendar date = Calendar.getInstance();date.setTime(nowTime);Calendar begin = Calendar.getInstance();begin.setTime(startTime);Calendar end = Calendar.getInstance();end.setTime(endTime);if (date.after(begin) && date.before(end)) {return true;} else {return false;}}public static Long getSeconds(Date date) {if (null == date) {return 0L;}String timestamp = String.valueOf(date.getTime() / 1000);return Long.valueOf(timestamp);}/*** @description: Date转LocalDateTime* @date: 2021/1/13 9:04* @param: [date]* @return: java.time.LocalDateTime*/public static LocalDateTime buildDate(Date date) {Instant instant = date.toInstant();ZoneId zoneId = ZoneId.systemDefault();LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();return localDateTime;}
}
批量文件压缩下载
import com.cnooc.lpg.cylinder.vo.ExportQRCodeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;import org.apache.commons.io.FileUtils;/*** @description: 批量文件压缩下载* @author: shilf3* @date: 2021/1/15 9:19*/
@Component
@Slf4j
public class DowloadZipUtil {//跳过https证书认证static {try {trustAllHttpsCertificates();HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {public boolean verify(String urlHostName, SSLSession session) {return true;}});} catch (Exception e) {}}/*** @description: 批量文件压缩下载* @date: 2021/1/15 11:29* @param: [urlList, zipName, response, request] 需要批量下载文件的链接地址列表,输出的压缩包名称* @return: void*/public static void downZip(List<ExportQRCodeVO> urlList, String zipName, HttpServletResponse response, HttpServletRequest request) throws Exception {//响应头的设置response.reset();response.setCharacterEncoding("utf-8");response.setContentType("application/x-zip-compressed");String downloadName = zipName + ".zip";downloadName = URLEncoder.encode(downloadName, "UTF-8");response.setHeader("Content-Disposition", "attachment;fileName=" + downloadName);//设置压缩流:直接写入response,实现边压缩边下载ZipOutputStream zipos = null;DataOutputStream os = null;InputStream in = null;InputStream is = null;InputStream bis = null;try {zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法//循环将文件写入压缩流os = null;for (ExportQRCodeVO code : urlList) {URL link = new URL(code.getImgUrl());String filename = code.getQrCodeNumber() + ".png";//添加ZipEntry,并ZipEntry中写入文件流zipos.putNextEntry(new ZipEntry(filename));os = new DataOutputStream(zipos);//https打开流 失败bis = new BufferedInputStream(link.openStream());byte[] b = new byte[1024];int length = 0;while ((length = bis.read(b)) != -1) {os.write(b, 0, length);}zipos.closeEntry();}//将excel文件写入压缩流in = EasyPoiUtil.getExcelInputStream(urlList, "钢瓶二维码", ExportQRCodeVO.class);zipos.putNextEntry(new ZipEntry("钢瓶二维码.xls"));os = new DataOutputStream(zipos);is = new BufferedInputStream(in);byte[] b = new byte[1024];int length = 0;while ((length = is.read(b)) != -1) {os.write(b, 0, length);}zipos.closeEntry();} finally {if (os != null) {os.flush();os.close();}if (zipos != null) {zipos.close();}if (in != null) {in.close();}if (is != null) {is.close();}if (bis != null) {bis.close();}}}private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {TrustManager[] trustAllCerts = new TrustManager[1];trustAllCerts[0] = new TrustAllManager();SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, trustAllCerts, null);HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());}private static class TrustAllManager implements X509TrustManager {public X509Certificate[] getAcceptedIssuers() {return null;}public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {}public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {}}
}
通用http工具封装
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.servlet.ServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;/*** 通用http工具封装* **/
public class HttpHelper
{private static final Logger LOGGER = LoggerFactory.getLogger(HttpHelper.class);public static String getBodyString(ServletRequest request){StringBuilder sb = new StringBuilder();BufferedReader reader = null;try (InputStream inputStream = request.getInputStream()){reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));String line = "";while ((line = reader.readLine()) != null){sb.append(line);}}catch (IOException e){LOGGER.warn("getBodyString出现问题!");}finally{if (reader != null){try{reader.close();}catch (IOException e){LOGGER.error(ExceptionUtils.getMessage(e));}}}return sb.toString();}
}
图片操作工具类
import sun.font.FontDesignMetrics;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;/*** @description: 图片操作工具类* @date: 2021/1/13 15:46*/
public class ImageUtil {/*** 待合并的两张图必须满足这样的前提,如果水平方向合并,则高度必须相等;如果是垂直方向合并,宽度必须相等。* mergeImage方法不做判断,自己判断。** @param img1         待合并的第一张图* @param img2         带合并的第二张图* @param isHorizontal 为true时表示水平方向合并,为false时表示垂直方向合并* @return 返回合并后的BufferedImage对象* @throws IOException*/public static BufferedImage mergeImage(BufferedImage img1, BufferedImage img2, BufferedImage img3,BufferedImage img0, boolean isHorizontal) throws IOException {int w0 = img0.getWidth();int h0 = img0.getHeight();int w1 = img1.getWidth();int h1 = img1.getHeight();int w2 = img2.getWidth();int h2 = img2.getHeight();int w3 = img3.getWidth();int h3 = img3.getHeight();// 从图片中读取RGBint[] ImageArrayOne = new int[w1 * h1];ImageArrayOne = img1.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中int[] ImageArrayTwo = new int[w2 * h2];ImageArrayTwo = img2.getRGB(0, 0, w2, h2, ImageArrayTwo, 0, w2);int[] ImageArrayThree = new int[w3 * h3];ImageArrayThree = img3.getRGB(0, 0, w3, h3, ImageArrayThree, 0, w3);int[] ImageArrayZero = new int[w0 * h0];ImageArrayZero = img0.getRGB(0, 0, w0, h0, ImageArrayZero, 0, w0);// 生成新图片BufferedImage DestImage = null;if (isHorizontal) { // 水平方向合并DestImage = new BufferedImage(w1 + w2, h1, BufferedImage.TYPE_INT_RGB);DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGBDestImage.setRGB(w1, 0, w2, h2, ImageArrayTwo, 0, w2);} else { // 垂直方向合并DestImage = new BufferedImage(w0, h0 + h1 + h2 + h3, BufferedImage.TYPE_INT_RGB);DestImage.setRGB(0, 0, w0, h0, ImageArrayZero, 0, w0); // 设置上半部分或左半部分的RGBDestImage.setRGB(0, h0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGBDestImage.setRGB(0, h0 + h1, w2, h2, ImageArrayTwo, 0, w2); // 设置下半部分的RGBDestImage.setRGB(0, h0 + h1 + h2, w3, h3, ImageArrayThree, 0, w3); // 设置下半部分的RGB}return DestImage;}/*** @description: BufferedImage转二进制数组* @date: 2021/1/13 16:06* @param: [image]* @return: byte[] 二进制字节数组*/public static byte[] BufferedImage2Byte(BufferedImage image) throws IOException {ByteArrayOutputStream baos = new ByteArrayOutputStream();ImageIO.write(image, "png", baos);baos.flush();//使用toByteArray()方法转换成字节数组byte[] imageInByte = baos.toByteArray();baos.close();return imageInByte;}/*** @description: 文字转图片* @date: 2021/1/14 8:49* @param: [text, width, height]* @return: java.awt.image.BufferedImage*/public static BufferedImage text2Img(String text, Integer width, Integer height) {//定义字体Font font = new Font("微软雅黑", Font.PLAIN, 30);BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);Graphics g = image.getGraphics();//设置画布大小,颜色,背景,背景颜色,字体g.setClip(0, 0, width, height);g.setColor(Color.white);g.fillRect(0, 0, width, height);g.setColor(Color.black);g.setFont(font);//计算该字体文本的长度int wordWidth = getWordWidth(font, text);//居中写入,x:左偏移量,y:上偏移量g.drawString(text, (width - wordWidth) / 2, 35);g.dispose();return image;}/*** @description: 计算字体长度* @date: 2021/1/14 8:49* @param: [font, content]* @return: int*/private static int getWordWidth(Font font, String content) {FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);int width = 0;for (int i = 0; i < content.length(); i++) {width += metrics.charWidth(content.charAt(i));}return width;}
}
客户端工具类
import com.cnooc.lpg.cylinder.core.text.Convert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;/*** 客户端工具类* * */
public class ServletUtils
{/*** 获取String参数*/public static String getParameter(String name){return getRequest().getParameter(name);}/*** 获取String参数*/public static String getParameter(String name, String defaultValue){return Convert.toStr(getRequest().getParameter(name), defaultValue);}/*** 获取Integer参数*/public static Integer getParameterToInt(String name){return Convert.toInt(getRequest().getParameter(name));}/*** 获取Integer参数*/public static Integer getParameterToInt(String name, Integer defaultValue){return Convert.toInt(getRequest().getParameter(name), defaultValue);}/*** 获取request*/public static HttpServletRequest getRequest(){return getRequestAttributes().getRequest();}/*** 获取response*/public static HttpServletResponse getResponse(){return getRequestAttributes().getResponse();}/*** 获取session*/public static HttpSession getSession(){return getRequest().getSession();}public static ServletRequestAttributes getRequestAttributes(){RequestAttributes attributes = RequestContextHolder.getRequestAttributes();return (ServletRequestAttributes) attributes;}/*** 将字符串渲染到客户端* * @param response 渲染对象* @param string 待渲染的字符串* @return null*/public static String renderString(HttpServletResponse response, String string){try{response.setStatus(200);response.setContentType("application/json");response.setCharacterEncoding("utf-8");response.getWriter().print(string);}catch (IOException e){e.printStackTrace();}return null;}/*** 是否是Ajax异步请求* * @param request*/public static boolean isAjaxRequest(HttpServletRequest request){String accept = request.getHeader("accept");if (accept != null && accept.indexOf("application/json") != -1){return true;}String xRequestedWith = request.getHeader("X-Requested-With");if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1){return true;}String uri = request.getRequestURI();if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")){return true;}String ajax = request.getParameter("__ajax");if (StringUtils.inStringIgnoreCase(ajax, "json", "xml")){return true;}return false;}
}
字符串工具类
import com.cnooc.lpg.cylinder.core.text.StrFormatter;import java.util.*;/*** 字符串工具类* **/
public class StringUtils extends org.apache.commons.lang3.StringUtils
{/** 空字符串 */private static final String NULLSTR = "";/** 下划线 */private static final char SEPARATOR = '_';/*** 获取参数不为空值* * @param value defaultValue 要判断的value* @return value 返回值*/public static <T> T nvl(T value, T defaultValue){return value != null ? value : defaultValue;}/*** * 判断一个Collection是否为空, 包含List,Set,Queue* * @param coll 要判断的Collection* @return true:为空 false:非空*/public static boolean isEmpty(Collection<?> coll){return isNull(coll) || coll.isEmpty();}/*** * 判断一个Collection是否非空,包含List,Set,Queue* * @param coll 要判断的Collection* @return true:非空 false:空*/public static boolean isNotEmpty(Collection<?> coll){return !isEmpty(coll);}/*** * 判断一个对象数组是否为空* * @param objects 要判断的对象数组** @return true:为空 false:非空*/public static boolean isEmpty(Object[] objects){return isNull(objects) || (objects.length == 0);}/*** * 判断一个对象数组是否非空* * @param objects 要判断的对象数组* @return true:非空 false:空*/public static boolean isNotEmpty(Object[] objects){return !isEmpty(objects);}/*** * 判断一个Map是否为空* * @param map 要判断的Map* @return true:为空 false:非空*/public static boolean isEmpty(Map<?, ?> map){return isNull(map) || map.isEmpty();}/*** * 判断一个Map是否为空* * @param map 要判断的Map* @return true:非空 false:空*/public static boolean isNotEmpty(Map<?, ?> map){return !isEmpty(map);}/*** * 判断一个字符串是否为空串* * @param str String* @return true:为空 false:非空*/public static boolean isEmpty(String str){return isNull(str) || NULLSTR.equals(str.trim());}/*** * 判断一个字符串是否为非空串* * @param str String* @return true:非空串 false:空串*/public static boolean isNotEmpty(String str){return !isEmpty(str);}/*** * 判断一个对象是否为空* * @param object Object* @return true:为空 false:非空*/public static boolean isNull(Object object){return object == null;}/*** * 判断一个对象是否非空* * @param object Object* @return true:非空 false:空*/public static boolean isNotNull(Object object){return !isNull(object);}/*** * 判断一个对象是否是数组类型(Java基本型别的数组)* * @param object 对象* @return true:是数组 false:不是数组*/public static boolean isArray(Object object){return isNotNull(object) && object.getClass().isArray();}/*** 去空格*/public static String trim(String str){return (str == null ? "" : str.trim());}/*** 截取字符串* * @param str 字符串* @param start 开始* @return 结果*/public static String substring(final String str, int start){if (str == null){return NULLSTR;}if (start < 0){start = str.length() + start;}if (start < 0){start = 0;}if (start > str.length()){return NULLSTR;}return str.substring(start);}/*** 截取字符串* * @param str 字符串* @param start 开始* @param end 结束* @return 结果*/public static String substring(final String str, int start, int end){if (str == null){return NULLSTR;}if (end < 0){end = str.length() + end;}if (start < 0){start = str.length() + start;}if (end > str.length()){end = str.length();}if (start > end){return NULLSTR;}if (start < 0){start = 0;}if (end < 0){end = 0;}return str.substring(start, end);}/*** 格式化文本, {} 表示占位符<br>* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>* 例:<br>* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>* * @param template 文本模板,被替换的部分用 {} 表示* @param params 参数值* @return 格式化后的文本*/public static String format(String template, Object... params){if (isEmpty(params) || isEmpty(template)){return template;}return StrFormatter.format(template, params);}/*** 字符串转set* * @param str 字符串* @param sep 分隔符* @return set集合*/public static final Set<String> str2Set(String str, String sep){return new HashSet<String>(str2List(str, sep, true, false));}/*** 字符串转list* * @param str 字符串* @param sep 分隔符* @param filterBlank 过滤纯空白* @param trim 去掉首尾空白* @return list集合*/public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim){List<String> list = new ArrayList<String>();if (StringUtils.isEmpty(str)){return list;}// 过滤空白字符串if (filterBlank && StringUtils.isBlank(str)){return list;}String[] split = str.split(sep);for (String string : split){if (filterBlank && StringUtils.isBlank(string)){continue;}if (trim){string = string.trim();}list.add(string);}return list;}/*** 下划线转驼峰命名*/public static String toUnderScoreCase(String str){if (str == null){return null;}StringBuilder sb = new StringBuilder();// 前置字符是否大写boolean preCharIsUpperCase = true;// 当前字符是否大写boolean curreCharIsUpperCase = true;// 下一字符是否大写boolean nexteCharIsUpperCase = true;for (int i = 0; i < str.length(); i++){char c = str.charAt(i);if (i > 0){preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));}else{preCharIsUpperCase = false;}curreCharIsUpperCase = Character.isUpperCase(c);if (i < (str.length() - 1)){nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));}if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase){sb.append(SEPARATOR);}else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase){sb.append(SEPARATOR);}sb.append(Character.toLowerCase(c));}return sb.toString();}/*** 是否包含字符串* * @param str 验证字符串* @param strs 字符串组* @return 包含返回true*/public static boolean inStringIgnoreCase(String str, String... strs){if (str != null && strs != null){for (String s : strs){if (str.equalsIgnoreCase(trim(s))){return true;}}}return false;}/*** 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld* * @param name 转换前的下划线大写方式命名的字符串* @return 转换后的驼峰式命名的字符串*/public static String convertToCamelCase(String name){StringBuilder result = new StringBuilder();// 快速检查if (name == null || name.isEmpty()){// 没必要转换return "";}else if (!name.contains("_")){// 不含下划线,仅将首字母大写return name.substring(0, 1).toUpperCase() + name.substring(1);}// 用下划线将原始字符串分割String[] camels = name.split("_");for (String camel : camels){// 跳过原始字符串中开头、结尾的下换线或双重下划线if (camel.isEmpty()){continue;}// 首字母大写result.append(camel.substring(0, 1).toUpperCase());result.append(camel.substring(1).toLowerCase());}return result.toString();}/*** 驼峰式命名法 例如:user_name->userName*/public static String toCamelCase(String s){if (s == null){return null;}s = s.toLowerCase();StringBuilder sb = new StringBuilder(s.length());boolean upperCase = false;for (int i = 0; i < s.length(); i++){char c = s.charAt(i);if (c == SEPARATOR){upperCase = true;}else if (upperCase){sb.append(Character.toUpperCase(c));upperCase = false;}else{sb.append(c);}}return sb.toString();}@SuppressWarnings("unchecked")public static <T> T cast(Object obj){return (T) obj;}
}
easypoi导出word工具类
import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.Assert;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;/*** @description: easypoi导出word工具类* @date: 2021/1/18 8:36*/
public class WordUtil {/*** @description: 导出word文档* @date: 2021/1/18 8:36* @param: response 响应* @param: templatePath easypoi word模板* @param: fileName 文件名称* @param: params 替换参数* @return: void*/public static void exportWord(HttpServletResponse response, String templatePath, String fileName, Map<String, Object> params) throws Exception {Assert.notNull(templatePath, "模板路径不能为空");Assert.notNull(fileName, "导出文件名不能为空");Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);OutputStream output = response.getOutputStream();response.setCharacterEncoding("UTF-8");response.setContentType("application/msword");response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));doc.write(output);output.close();}
}
文件上传下载工具类
import cn.hutool.core.util.ReUtil;
import org.apache.commons.lang3.StringUtils;import java.io.File;
import java.math.BigDecimal;
import java.util.regex.Pattern;/***** @since:oss-server 1.0* @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a> * 2018/06/11 13:38*/
public class FileUtils {public static final int KB_SIZE = 1024;public static final int MB_SIZE = 1024 * KB_SIZE;public static final int GB_SIZE = 1024 * MB_SIZE;/*** file unmodified* @param file*/public static void fileUnModified(File file){if (file!=null){file.setWritable(false);file.setExecutable(false);file.setReadOnly();}}/**** 获取文件大小* @param file* @return*/public static long getFileSize(File file){long size=0L;if (file.exists()){if (!file.isDirectory()){size=file.length();}else{size+=getDirSize(file);}}return size;}public static long getDirSize(File file){long dirsize=0l;if (file!=null){if (file.exists()){if (file.isDirectory()){File[] files=file.listFiles();for (File fl:files){if (fl.isDirectory()){dirsize+=getDirSize(fl);}else{dirsize+=fl.length();}}}}}return dirsize;}/**** byte字节转换为字符串* @param fileBytes* @return*/public static String byteToString(long fileBytes){StringBuffer byteStr=new StringBuffer();BigDecimal fullSize=new BigDecimal(fileBytes);//mbBigDecimal mbSize=new BigDecimal(MB_SIZE);float gbsize=fullSize.divide(new BigDecimal(GB_SIZE),2,BigDecimal.ROUND_HALF_UP).floatValue();if (gbsize>1){byteStr.append(gbsize).append("GB");}else{float dvsize=fullSize.divide(mbSize,2,BigDecimal.ROUND_HALF_UP).floatValue();if (dvsize>1){byteStr.append(dvsize).append("MB");}else{//kb显示BigDecimal kbSize=new BigDecimal(KB_SIZE);byteStr.append(fullSize.divide(kbSize,2,BigDecimal.ROUND_HALF_UP).floatValue()).append("KB");}}return byteStr.toString();}/*** 获取文件类型* @param file* @return*/public static String getFileType(File file){String type="文件";if (file.isDirectory()){type="文件夹";}else{String fileName=file.getName();//判断是否有后缀if (StringUtils.isNotBlank(fileName)){if (fileName.contains(".")){String suffix=fileName.substring(fileName.lastIndexOf(".")+1);type=suffix.toUpperCase()+" 文件";}}}return type;}public static String getMediaType(File file){String mediaType="text";if (file.isDirectory()){mediaType="dir";}else{String fileName=file.getName();//判断是否有后缀if (StringUtils.isNotBlank(fileName)){if (fileName.contains(".")){String suffix=fileName.substring(fileName.lastIndexOf(".")+1);mediaType=suffix.toLowerCase();}}}return mediaType;}public static String transforSysSpec(String path){//获取操作系统String regex=".*?window.*";String nPath="";if (ReUtil.isMatch(Pattern.compile(regex,Pattern.CASE_INSENSITIVE),System.getProperty("os.name"))){//如果是windowsnPath=path.replaceAll("\\\\","/");}else{nPath=path;}return nPath;}public static void main(String[] args) {File file=new File("D:\\无标题.xls");System.out.println(getFileType(file));System.out.println(getFileSize(file));System.out.println(byteToString(getDirSize(file)));System.out.println(System.getProperty("os.name"));}
}---------------(这里是第二个类)--------------------import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;/**** @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a>*/
public class CommonUtils {public static  String getIpAddr(HttpServletRequest request) {String ipAddress = null;// ipAddress = this.getRequest().getRemoteAddr();ipAddress = request.getHeader("x-forwarded-for");if (ipAddress == null || ipAddress.length() == 0|| "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getHeader("Proxy-Client-IP");}if (ipAddress == null || ipAddress.length() == 0|| "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getHeader("WL-Proxy-Client-IP");}if (ipAddress == null || ipAddress.length() == 0|| "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getRemoteAddr();if (ipAddress.equals("127.0.0.1")) {// 根据网卡取本机配置的IPInetAddress inet = null;try {inet = InetAddress.getLocalHost();} catch (UnknownHostException e) {e.printStackTrace();}ipAddress = inet.getHostAddress();}}// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()// = 15if (ipAddress.indexOf(",") > 0) {ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));}}return ipAddress;}/*** 判断图片格式* @param type* @return*/public static boolean isFileType(String type){boolean bl = false;String [] imageType = new String[]{"JPG","BMP","PCX","TIFF","GIF","JPEG","TGA","EXIF","FPX","SVG","PSD","CDR","PCD","DXF","UFO","EPS","AI","PNG","HDRI","RAW"};for(int i = 0;i<imageType.length;i++){if(imageType[i].equals(type)){bl = true;}}return bl;}
}

本文链接:https://my.lmcjl.com/post/13082.html

展开阅读全文

4 评论

留下您的评论.