1.Cookie工具类
package com.wang.utils;
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;
public final class CookieUtils {
protected static final Logger logger = LoggerFactory.getLogger(CookieUtils.class);
public static String getCookieValue(HttpServletRequest request, String cookieName) {
return getCookieValue(request, cookieName, false);
}
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;
}
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;
}
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue) {
setCookie(request, response, cookieName, cookieValue, -1);
}
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage) {
setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
}
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, boolean isEncode) {
setCookie(request, response, cookieName, cookieValue, -1, isEncode);
}
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
}
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
}
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
doSetCookie(request, response, cookieName, "", -1, false);
}
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
try {
if (cookieValue == null) {
cookieValue = "";
} else if (isEncode) {
cookieValue = URLEncoder.encode(cookieValue, "utf-8");
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0) {
cookie.setMaxAge(cookieMaxage);
}
if (null != request)
{
cookie.setDomain(getDomainName(request));
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
logger.error("Cookie Encode Error.", e);
}
}
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
try {
if (cookieValue == null) {
cookieValue = "";
} else {
cookieValue = URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0) {
cookie.setMaxAge(cookieMaxage);
}
if (null != request)
{
cookie.setDomain(getDomainName(request));
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
logger.error("Cookie Encode Error.", e);
}
}
private static final String getDomainName(HttpServletRequest request) {
String domainName = null;
String serverName = request.getRequestURL().toString();
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) {
domainName = domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
} else if (len <= 3 && len > 1) {
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;
}
}
2.文件下载工具类
package com.example.utils;
import com.example.common.lang.ResultEnum;
import com.example.exception.GlobalException;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Encoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class DownloadFileUtil {
public static void downloadFile(String originalFileName, File file, HttpServletResponse response, HttpServletRequest request) {
checkParam(originalFileName, file);
response.reset();
response.setContentLength((int) file.length());
response.setContentType("multipart/form-data;charset=UTF-8");
String encodedFilename = getEncodedFilename(request, originalFileName);
response.addHeader("Content-Disposition", "attachment;filename=" + encodedFilename);
FileInputStream fileInputStream = null;
ServletOutputStream outputStream = null;
try {
fileInputStream = new FileInputStream(file);
byte[] buffers = new byte[1024];
outputStream = response.getOutputStream();
int length;
while ((length = fileInputStream.read(buffers)) > 0) {
outputStream.write(buffers, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void checkParam(String originalFileName, File file) {
if(StringUtils.isEmpty(originalFileName)){
throw new GlobalException(ResultEnum.FILENAME_EMPTY);
}
if(file == null || !file.exists() ){
throw new GlobalException(ResultEnum.FILE_ERROR);
}
}
private static String getEncodedFilename(HttpServletRequest request, String originalFileName) {
String encodedFilename = null;
String agent = request.getHeader("User-Agent");
if(agent.contains("MSIE")){
try {
encodedFilename = URLEncoder.encode(originalFileName, "utf-8");
encodedFilename = encodedFilename.replace("+", " ");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else if(agent.contains("Firefox")){
BASE64Encoder base64Encoder = new BASE64Encoder();
encodedFilename = "=?utf-8?B?" + base64Encoder.encode(originalFileName.getBytes(StandardCharsets.UTF_8))+"?=";
}else{
try {
encodedFilename = URLEncoder.encode(originalFileName, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return encodedFilename;
}
}
3.AES加密工具类
package com.example.utils;
import cn.hutool.crypto.SecureUtil;
import com.example.common.lang.WebConst;
public class PasswordUtil {
public static String encrypt(String password, String salt) throws Exception {
return AesUtils.encrypt(SecureUtil.md5(salt + WebConst.SECURITY_KEY), password);
}
public static String decrypt(String encryptPassword, String salt) throws Exception {
return AesUtils.decrypt(SecureUtil.md5(salt + WebConst.SECURITY_KEY), encryptPassword);
}
}
package com.example.utils;
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class AesUtils {
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
public static String encrypt(String passwd, String content) throws Exception {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(passwd));
byte[] result = cipher.doFinal(byteContent);
return Base64.encodeBase64String(result);
}
public static String decrypt(String passwd, String encrypted) throws Exception {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(passwd));
byte[] result = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(result, "utf-8");
}
private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(password.getBytes());
kg.init(128, random);
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
}
}
4.IP工具类
package com.example.utils;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class IPKit {
public static String getIpAddrByRequest(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
public static String getRealIp() throws SocketException {
String localip = null;
String netip = null;
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
boolean finded = false;
while (netInterfaces.hasMoreElements() && !finded) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = address.nextElement();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) {
netip = ip.getHostAddress();
finded = true;
break;
} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) {
localip = ip.getHostAddress();
}
}
}
if (netip != null && !"".equals(netip)) {
return netip;
} else {
return localip;
}
}
}
5.JwtToken工具类
package com.example.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "example.jwt")
public class JwtUtils {
private String secret;
private long expire;
private String header;
public String generateToken(long userId) {
Date nowDate = new Date();
Date expireTime = new Date(nowDate.getTime() + expire * 1000);
return Jwts.builder()
.setHeaderParam("tye", "JWT")
.setSubject(userId + "")
.setIssuedAt(nowDate)
.setExpiration(expireTime)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public Claims getClaimByToken(String token) {
try {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
log.debug("validate is token error ", e);
return null;
}
}
public boolean isTokenExpired(Date expiration) {
return expiration.before(new Date());
}
}
6.POI操作Excel工具类
package com.example.utils;
import com.example.common.cond.PageHelper;
import com.example.common.cond.SentencesCond;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Slf4j
public class WriterExcelFile {
public static boolean generateWorkbook(String path, String name, List<String> titles, PageHelper<SentencesCond> values) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet(name);
sheet.setDefaultColumnWidth((short) 10);
Row row = sheet.createRow(0);
for (int i = 0; i < titles.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellValue(titles.get(i));
}
for (int index = 1; index <= values.getTotal(); ++index) {
row = sheet.createRow(index);
for (int i = 0; i < titles.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellValue(titles.get(i));
}
}
boolean isCorrect = false;
File file = new File(path);
if (file.exists()) {
file.deleteOnExit();
file = new File(path);
}
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
workbook.write(outputStream);
isCorrect = true;
} catch (IOException e) {
log.error(e.getMessage());
} finally {
try {
if (null != outputStream) {
outputStream.close();
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
return isCorrect;
}
private static Map<String, CellStyle> createStyles(Workbook wb) {
Map<String, CellStyle> styles = Maps.newHashMap();
DataFormat dataFormat = wb.createDataFormat();
CellStyle titleStyle = wb.createCellStyle();
titleStyle.setAlignment(HorizontalAlignment.CENTER);
titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
titleStyle.setLocked(true);
titleStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
titleStyle.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
Font titleFont = wb.createFont();
titleFont.setFontHeightInPoints((short) 16);
titleFont.setBold(true);
titleFont.setFontName("微软雅黑");
titleStyle.setFont(titleFont);
styles.put("title", titleStyle);
CellStyle headerStyle = wb.createCellStyle();
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headerStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerStyle.setWrapText(true);
Font headerFont = wb.createFont();
headerFont.setFontHeightInPoints((short) 12);
headerFont.setColor(IndexedColors.WHITE.getIndex());
titleFont.setFontName("微软雅黑");
headerStyle.setFont(headerFont);
styles.put("header", headerStyle);
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyle.setWrapText(true);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
styles.put("cell", cellStyle);
return styles;
}
}
7.EasyExcel根据实体类写入Excel
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.0-beta2</version>
</dependency>
- 实体类
@ExcelProperty(value = "xxx",index = 0)
中index为列号,value为列名
@ExcelIgnore
表示忽略这一列
package com.example.common.cond;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
@Data
public class ExcelCond {
@ExcelProperty(value = "设备名称",index = 0)
private String dname;
@ExcelProperty(value = "功能名",index = 1)
private String fname;
@ExcelProperty(value = "测试语句",index = 2)
private String content;
}
public static String objectListToExcel(List<ExcelCond> excelConds) {
String path = System.getProperty("user.dir");
String localPath = path + "/src/main/java/com/example/excel/";
String fileName = localPath + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
EasyExcel.write(fileName, ExcelCond.class).sheet("hello").doWrite(excelConds);
return fileName;
}