Java項(xiàng)目常見(jiàn)工具類(lèi)詳解
JWT工具類(lèi)
這里一共涉及四個(gè)方法:
傳入用戶(hù)信息獲得token
傳入token字符串判斷token是否存在與有效
傳入HttpServletRequest,通過(guò)獲取Header中的token判斷是否存在與有效
根據(jù)token獲取用戶(hù)id
public class JwtUtils { //token過(guò)期時(shí)間 public static final long EXPIRE = 1000 * 60 * 60 * 24; //秘鑰 public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO"; /** * 獲得token * * @param id 用戶(hù)id * @param nickname 用戶(hù)昵稱(chēng) * @return */ public static String getJwtToken(String id, String nickname) { String JwtToken = Jwts.builder() //設(shè)置jwt頭信息 .setHeaderParam("typ", "JWT") .setHeaderParam("alg", "HS256") //設(shè)置分類(lèi) .setSubject("guli-user") //設(shè)置簽發(fā)時(shí)間 .setIssuedAt(new Date()) //設(shè)置過(guò)期時(shí)間=當(dāng)前時(shí)間+過(guò)多久過(guò)期的時(shí)間 .setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) //設(shè)置token主體部分,存儲(chǔ)用戶(hù)信息 .claim("id", id) .claim("nickname", nickname) //設(shè)置簽發(fā)算法+秘鑰 .signWith(SignatureAlgorithm.HS256, APP_SECRET) .compact(); return JwtToken; } /** * 判斷token是否存在與有效 * * @param jwtToken * @return */ public static boolean checkToken(String jwtToken) { if (StringUtils.isEmpty(jwtToken)) return false; try { //驗(yàn)證token是否是有效的token Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 判斷token是否存在與有效 * * @param request * @return */ public static boolean checkToken(HttpServletRequest request) { try { String jwtToken = request.getHeader("token"); if (StringUtils.isEmpty(jwtToken)) { return false; } Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 根據(jù)token獲取會(huì)員id * * @param request * @return */ public static String getMemberIdByJwtToken(HttpServletRequest request) { String jwtToken = request.getHeader("token"); if (StringUtils.isEmpty(jwtToken)) return ""; Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken); Claims claims = claimsJws.getBody(); return (String) claims.get("id"); } }
MD5工具類(lèi)
public final class MD5 { /** * 傳入字符串,返回經(jīng)過(guò)MD5加密的后的字符串 * * @param strSrc 需要加密的字符串 * @return 返回加密后的字符串 */ public static String encrypt(String strSrc) { try { //用來(lái)將字節(jié)轉(zhuǎn)換成 16 進(jìn)制表示的字符 char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; byte[] bytes = strSrc.getBytes(); //得到實(shí)現(xiàn)指定摘要算法的 MessageDigest對(duì)象 MessageDigest md = MessageDigest.getInstance("MD5"); //使用指定的 byte數(shù)組更新摘要 md.update(bytes); //通過(guò)執(zhí)行諸如填充之類(lèi)的最終操作完成哈希計(jì)算。在調(diào)用此方法之后,摘要被重置 bytes = md.digest(); int j = bytes.length; char[] chars = new char[j * 2]; int k = 0; //從第一個(gè)字節(jié)開(kāi)始,對(duì)每一個(gè)字節(jié),轉(zhuǎn)換成 16 進(jìn)制字符 for (int i = 0; i < bytes.length; i++) { //取第 i 個(gè)字節(jié) byte b = bytes[i]; //取字節(jié)中高 4 位的數(shù)字轉(zhuǎn)換 chars[k++] = hexChars[b >>> 4 & 0xf]; //取字節(jié)中低 4 位的數(shù)字轉(zhuǎn)換 chars[k++] = hexChars[b & 0xf]; } //將轉(zhuǎn)換的結(jié)果轉(zhuǎn)換為字符串返回 return new String(chars); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException("MD5加密出錯(cuò)!!+" + e); } } public static void main(String[] args) { System.out.println(MD5.encrypt("111111")); } }
視頻點(diǎn)播工具類(lèi)
得到視頻點(diǎn)播需要的初始化對(duì)象DefaultAcsClient:
public class InitVodCilent { /** * 得到視頻點(diǎn)播需要的client * * @param accessKeyId id * @param accessKeySecret 秘鑰 * @return 返回DefaultAcsClient對(duì)象 * @throws ClientException */ public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException { //點(diǎn)播服務(wù)接入?yún)^(qū)域 String regionId = "cn-shanghai"; DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret); DefaultAcsClient client = new DefaultAcsClient(profile); return client; } }
公共常量工具類(lèi)
對(duì)于一些微信支付和阿里云OSS等有許多固定地址的,我們可以使用一個(gè)工具類(lèi)定義為常量,方便獲取
這里舉個(gè)栗子
先在配置文件定義:
# 微信開(kāi)放平臺(tái) appid wx.open.app_id=wxed995adadav4c01bb89b47 # 微信開(kāi)放平臺(tái) appsecret wx.open.app_secret=a748251723ad5173ddbsfa4083788de60b90e # 微信開(kāi)放平臺(tái) 重定向url wx.open.redirect_url=http://localhost:8160/api/ucenter/wx/callback
配置類(lèi):
@Component public class ConstantWxUtils implements InitializingBean { @Value("${wx.open.app_id}") private String appId; @Value("${wx.open.app_secret}") private String appSecret; @Value("${wx.open.redirect_url}") private String redirectUrl; //微信開(kāi)放平臺(tái) appid public static String WX_OPEN_APP_ID; //微信開(kāi)放平臺(tái) appsecret public static String WX_OPEN_APP_SECRET; //微信開(kāi)放平臺(tái) 重定向url public static String WX_OPEN_REDIRECT_URL; //保證了這些值已經(jīng)從配置文件讀取了,在進(jìn)行操作 @Override public void afterPropertiesSet() throws Exception { WX_OPEN_APP_ID = appId; WX_OPEN_APP_SECRET = appSecret; WX_OPEN_REDIRECT_URL = redirectUrl; } }
日期操作工具類(lèi)
這里一共涉及二個(gè)方法:
格式化Date日期,轉(zhuǎn)換為字符串返回
在日期date上增加amount天,返回Data
public class DateUtil { private static final String dateFormat = "yyyy-MM-dd"; /** * 格式化日期 * * @param date * @return */ public static String formatDate(Date date) { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); return sdf.format(date); } /** * 在日期date上增加amount天 * * @param date 處理的日期,非null * @param amount 要加的天數(shù),可能為負(fù)數(shù) */ public static Date addDays(Date date, int amount) { Calendar now = Calendar.getInstance(); now.setTime(date); now.set(Calendar.DATE, now.get(Calendar.DATE) + amount); return now.getTime(); } public static void main(String[] args) { System.out.println(DateUtil.formatDate(new Date())); System.out.println(DateUtil.formatDate(DateUtil.addDays(new Date(), -1))); } }
Http客戶(hù)端工具類(lèi)
封裝一個(gè)HttpClientUtils,可以實(shí)現(xiàn):
- 發(fā)送一個(gè) Post 請(qǐng)求
- 提交form表單
- 發(fā)送一個(gè) GET 請(qǐng)求
public class HttpClientUtils { public static final int connTimeout=10000; public static final int readTimeout=10000; public static final String charset="UTF-8"; private static HttpClient client = null; static { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(128); cm.setDefaultMaxPerRoute(128); client = HttpClients.custom().setConnectionManager(cm).build(); } public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{ return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout); } public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{ return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout); } public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException, SocketTimeoutException, Exception { return postForm(url, params, null, connTimeout, readTimeout); } public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception { return postForm(url, params, null, connTimeout, readTimeout); } public static String get(String url) throws Exception { return get(url, charset, null, null); } public static String get(String url, String charset) throws Exception { return get(url, charset, connTimeout, readTimeout); } /** * 發(fā)送一個(gè) Post 請(qǐng)求, 使用指定的字符集編碼 * * @param url 請(qǐng)求地址 * @param body RequestBody * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3 * @param charset 編碼 * @param connTimeout 建立鏈接超時(shí)時(shí)間,毫秒. * @param readTimeout 響應(yīng)超時(shí)時(shí)間,毫秒. * @return ResponseBody, 使用指定的字符集編碼. * @throws ConnectTimeoutException 建立鏈接超時(shí)異常 * @throws SocketTimeoutException 響應(yīng)超時(shí) * @throws Exception */ public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception { HttpClient client = null; //創(chuàng)建Http Post請(qǐng)求 HttpPost post = new HttpPost(url); String result = ""; try { if (StringUtils.isNotBlank(body)) { HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset)); post.setEntity(entity); } // 設(shè)置參數(shù) Builder customReqConf = RequestConfig.custom(); if (connTimeout != null) { customReqConf.setConnectTimeout(connTimeout); } if (readTimeout != null) { customReqConf.setSocketTimeout(readTimeout); } post.setConfig(customReqConf.build()); HttpResponse res; if (url.startsWith("https")) { // 執(zhí)行 Https 請(qǐng)求 client = createSSLInsecureClient(); res = client.execute(post); } else { // 執(zhí)行 Http 請(qǐng)求 client = HttpClientUtils.client; res = client.execute(post); } result = IOUtils.toString(res.getEntity().getContent(), charset); } finally { post.releaseConnection(); if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) { ((CloseableHttpClient) client).close(); } } return result; } /** * 提交form表單 * * @param url * @param params * @param connTimeout * @param readTimeout * @return * @throws ConnectTimeoutException * @throws SocketTimeoutException * @throws Exception */ public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception { HttpClient client = null; HttpPost post = new HttpPost(url); try { if (params != null && !params.isEmpty()) { List<NameValuePair> formParams = new ArrayList<NameValuePair>(); Set<Entry<String, String>> entrySet = params.entrySet(); for (Entry<String, String> entry : entrySet) { formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8); post.setEntity(entity); } if (headers != null && !headers.isEmpty()) { for (Entry<String, String> entry : headers.entrySet()) { post.addHeader(entry.getKey(), entry.getValue()); } } // 設(shè)置參數(shù) Builder customReqConf = RequestConfig.custom(); if (connTimeout != null) { customReqConf.setConnectTimeout(connTimeout); } if (readTimeout != null) { customReqConf.setSocketTimeout(readTimeout); } post.setConfig(customReqConf.build()); HttpResponse res = null; if (url.startsWith("https")) { // 執(zhí)行 Https 請(qǐng)求. client = createSSLInsecureClient(); res = client.execute(post); } else { // 執(zhí)行 Http 請(qǐng)求. client = HttpClientUtils.client; res = client.execute(post); } return IOUtils.toString(res.getEntity().getContent(), "UTF-8"); } finally { post.releaseConnection(); if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) { ((CloseableHttpClient) client).close(); } } } /** * 發(fā)送一個(gè) GET 請(qǐng)求 * * @param url * @param charset * @param connTimeout 建立鏈接超時(shí)時(shí)間,毫秒 * @param readTimeout 響應(yīng)超時(shí)時(shí)間,毫秒 * @return * @throws ConnectTimeoutException 建立鏈接超時(shí) * @throws SocketTimeoutException 響應(yīng)超時(shí) * @throws Exception */ public static String get(String url, String charset, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,SocketTimeoutException, Exception { HttpClient client = null; // 創(chuàng)建http GET請(qǐng)求 HttpGet get = new HttpGet(url); String result = ""; try { // 設(shè)置參數(shù) Builder customReqConf = RequestConfig.custom(); //設(shè)置鏈接超時(shí)時(shí)間,毫秒 if (connTimeout != null) { customReqConf.setConnectTimeout(connTimeout); } //設(shè)置響應(yīng)超時(shí)時(shí)間,毫秒 if (readTimeout != null) { customReqConf.setSocketTimeout(readTimeout); } get.setConfig(customReqConf.build()); HttpResponse res = null; if (url.startsWith("https")) { // 執(zhí)行 Https 請(qǐng)求 client = createSSLInsecureClient(); res = client.execute(get); } else { // 執(zhí)行 Http 請(qǐng)求 client = HttpClientUtils.client; res = client.execute(get); } result = IOUtils.toString(res.getEntity().getContent(), charset); } finally { get.releaseConnection(); if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) { ((CloseableHttpClient) client).close(); } } return result; } /** * 從 response 里獲取 charset * * @param ressponse * @return */ @SuppressWarnings("unused") private static String getCharsetFromResponse(HttpResponse ressponse) { // Content-Type:text/html; charset=GBK if (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) { String contentType = ressponse.getEntity().getContentType().getValue(); if (contentType.contains("charset=")) { return contentType.substring(contentType.indexOf("charset=") + 8); } } return null; } /** * 創(chuàng)建 SSL連接 * @return * @throws GeneralSecurityException */ private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } }); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (GeneralSecurityException e) { throw e; } } public static void main(String[] args) { try { String str= post("https://localhost:443/ssl/test.shtml","name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000); //String str= get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK"); /*Map<String,String> map = new HashMap<String,String>(); map.put("name", "111"); map.put("page", "222"); String str= postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);*/ System.out.println(str); } catch (ConnectTimeoutException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SocketTimeoutException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
獲取IP工具類(lèi)
根據(jù)request獲取請(qǐng)求的Ip地址:
/** * 根據(jù)request獲取請(qǐng)求的Ip地址 * */ @Slf4j public class IpUtils { /** * 獲取IP地址 * 使用Nginx等反向代理軟件, 則不能通過(guò)request.getRemoteAddr()獲取IP地址 * 如果使用了多級(jí)反向代理的話,X-Forwarded-For的值并不止一個(gè),而是一串IP地址,X-Forwarded-For中第一個(gè)非unknown的有效IP字符串,則為真實(shí)IP地址 */ public static String getIpAddr(HttpServletRequest request) { String ip = null, unknown = "unknown", seperator = ","; int maxLength = 15; try { ip = request.getHeader("x-forwarded-for"); if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } catch (Exception e) { log.error("IpUtils ERROR ", e); } // 使用代理,則獲取第一個(gè)IP地址 if (StringUtils.isEmpty(ip) && ip.length() > maxLength) { int idx = ip.indexOf(seperator); if (idx > 0) { ip = ip.substring(0, idx); } } return ip; } /** * 獲取ip地址 * * @return */ public static String getIpAddr() { HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); return getIpAddr(request); } }
獲取請(qǐng)求工具類(lèi):
/**
* 獲取請(qǐng)求工具類(lèi)
*/
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest(){
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}
以上就是Java項(xiàng)目常見(jiàn)工具類(lèi)詳解的詳細(xì)內(nèi)容,更多關(guān)于Java工具類(lèi)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringMVC 重定向參數(shù)RedirectAttributes實(shí)例
這篇文章主要介紹了SpringMVC 重定向參數(shù)RedirectAttributes實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Spring Boot日志技術(shù)logback原理及配置解析
這篇文章主要介紹了Spring Boot日志技術(shù)logback原理及用法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07Java通過(guò)MyBatis框架對(duì)MySQL數(shù)據(jù)進(jìn)行增刪查改的基本方法
MyBatis框架由Java的JDBC API進(jìn)一步封裝而來(lái),在操作數(shù)據(jù)庫(kù)方面效果拔群,接下來(lái)我們就一起來(lái)看看Java通過(guò)MyBatis框架對(duì)MySQL數(shù)據(jù)進(jìn)行增刪查改的基本方法:2016-06-06MyBatis處理mysql主鍵自動(dòng)增長(zhǎng)出現(xiàn)的不連續(xù)問(wèn)題解決
本文主要介紹了MyBatis處理mysql主鍵自動(dòng)增長(zhǎng)出現(xiàn)的不連續(xù)問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09Feign+mybatisplus搭建項(xiàng)目遇到的坑及解決
這篇文章主要介紹了Feign+mybatisplus搭建項(xiàng)目遇到的坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03深入了解Java語(yǔ)言中的并發(fā)性選項(xiàng)有何不同
這篇文章主要介紹了深入了解Java語(yǔ)言中的并發(fā)性選項(xiàng)有何不同,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,,需要的朋友可以參考下2019-06-06使用Spring Boot搭建Java web項(xiàng)目及開(kāi)發(fā)過(guò)程圖文詳解
這篇文章主要介紹了使用Spring Boot搭建Java web項(xiàng)目及開(kāi)發(fā)過(guò)程,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06Spring Cache和EhCache實(shí)現(xiàn)緩存管理方式
這篇文章主要介紹了Spring Cache和EhCache實(shí)現(xiàn)緩存管理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06