Java項目常見工具類詳解
JWT工具類
這里一共涉及四個方法:
傳入用戶信息獲得token
傳入token字符串判斷token是否存在與有效
傳入HttpServletRequest,通過獲取Header中的token判斷是否存在與有效
根據(jù)token獲取用戶id
public class JwtUtils {
//token過期時間
public static final long EXPIRE = 1000 * 60 * 60 * 24;
//秘鑰
public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";
/**
* 獲得token
*
* @param id 用戶id
* @param nickname 用戶昵稱
* @return
*/
public static String getJwtToken(String id, String nickname) {
String JwtToken = Jwts.builder()
//設置jwt頭信息
.setHeaderParam("typ", "JWT")
.setHeaderParam("alg", "HS256")
//設置分類
.setSubject("guli-user")
//設置簽發(fā)時間
.setIssuedAt(new Date())
//設置過期時間=當前時間+過多久過期的時間
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
//設置token主體部分,存儲用戶信息
.claim("id", id)
.claim("nickname", nickname)
//設置簽發(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 {
//驗證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獲取會員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工具類
public final class MD5 {
/**
* 傳入字符串,返回經過MD5加密的后的字符串
*
* @param strSrc 需要加密的字符串
* @return 返回加密后的字符串
*/
public static String encrypt(String strSrc) {
try {
//用來將字節(jié)轉換成 16 進制表示的字符
char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f'};
byte[] bytes = strSrc.getBytes();
//得到實現(xiàn)指定摘要算法的 MessageDigest對象
MessageDigest md = MessageDigest.getInstance("MD5");
//使用指定的 byte數(shù)組更新摘要
md.update(bytes);
//通過執(zhí)行諸如填充之類的最終操作完成哈希計算。在調用此方法之后,摘要被重置
bytes = md.digest();
int j = bytes.length;
char[] chars = new char[j * 2];
int k = 0;
//從第一個字節(jié)開始,對每一個字節(jié),轉換成 16 進制字符
for (int i = 0; i < bytes.length; i++) {
//取第 i 個字節(jié)
byte b = bytes[i];
//取字節(jié)中高 4 位的數(shù)字轉換
chars[k++] = hexChars[b >>> 4 & 0xf];
//取字節(jié)中低 4 位的數(shù)字轉換
chars[k++] = hexChars[b & 0xf];
}
//將轉換的結果轉換為字符串返回
return new String(chars);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new RuntimeException("MD5加密出錯??!+" + e);
}
}
public static void main(String[] args) {
System.out.println(MD5.encrypt("111111"));
}
}
視頻點播工具類
得到視頻點播需要的初始化對象DefaultAcsClient:
public class InitVodCilent {
/**
* 得到視頻點播需要的client
*
* @param accessKeyId id
* @param accessKeySecret 秘鑰
* @return 返回DefaultAcsClient對象
* @throws ClientException
*/
public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
//點播服務接入?yún)^(qū)域
String regionId = "cn-shanghai";
DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
return client;
}
}
公共常量工具類
對于一些微信支付和阿里云OSS等有許多固定地址的,我們可以使用一個工具類定義為常量,方便獲取
這里舉個栗子
先在配置文件定義:
# 微信開放平臺 appid wx.open.app_id=wxed995adadav4c01bb89b47 # 微信開放平臺 appsecret wx.open.app_secret=a748251723ad5173ddbsfa4083788de60b90e # 微信開放平臺 重定向url wx.open.redirect_url=http://localhost:8160/api/ucenter/wx/callback
配置類:
@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;
//微信開放平臺 appid
public static String WX_OPEN_APP_ID;
//微信開放平臺 appsecret
public static String WX_OPEN_APP_SECRET;
//微信開放平臺 重定向url
public static String WX_OPEN_REDIRECT_URL;
//保證了這些值已經從配置文件讀取了,在進行操作
@Override
public void afterPropertiesSet() throws Exception {
WX_OPEN_APP_ID = appId;
WX_OPEN_APP_SECRET = appSecret;
WX_OPEN_REDIRECT_URL = redirectUrl;
}
}
日期操作工具類
這里一共涉及二個方法:
格式化Date日期,轉換為字符串返回
在日期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ù),可能為負數(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客戶端工具類
封裝一個HttpClientUtils,可以實現(xiàn):
- 發(fā)送一個 Post 請求
- 提交form表單
- 發(fā)送一個 GET 請求
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ā)送一個 Post 請求, 使用指定的字符集編碼
*
* @param url 請求地址
* @param body RequestBody
* @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
* @param charset 編碼
* @param connTimeout 建立鏈接超時時間,毫秒.
* @param readTimeout 響應超時時間,毫秒.
* @return ResponseBody, 使用指定的字符集編碼.
* @throws ConnectTimeoutException 建立鏈接超時異常
* @throws SocketTimeoutException 響應超時
* @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請求
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ù)
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 請求
client = createSSLInsecureClient();
res = client.execute(post);
} else {
// 執(zhí)行 Http 請求
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ù)
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 請求.
client = createSSLInsecureClient();
res = client.execute(post);
} else {
// 執(zhí)行 Http 請求.
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ā)送一個 GET 請求
*
* @param url
* @param charset
* @param connTimeout 建立鏈接超時時間,毫秒
* @param readTimeout 響應超時時間,毫秒
* @return
* @throws ConnectTimeoutException 建立鏈接超時
* @throws SocketTimeoutException 響應超時
* @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請求
HttpGet get = new HttpGet(url);
String result = "";
try {
// 設置參數(shù)
Builder customReqConf = RequestConfig.custom();
//設置鏈接超時時間,毫秒
if (connTimeout != null) {
customReqConf.setConnectTimeout(connTimeout);
}
//設置響應超時時間,毫秒
if (readTimeout != null) {
customReqConf.setSocketTimeout(readTimeout);
}
get.setConfig(customReqConf.build());
HttpResponse res = null;
if (url.startsWith("https")) {
// 執(zhí)行 Https 請求
client = createSSLInsecureClient();
res = client.execute(get);
} else {
// 執(zhí)行 Http 請求
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工具類
根據(jù)request獲取請求的Ip地址:
/**
* 根據(jù)request獲取請求的Ip地址
*
*/
@Slf4j
public class IpUtils {
/**
* 獲取IP地址
* 使用Nginx等反向代理軟件, 則不能通過request.getRemoteAddr()獲取IP地址
* 如果使用了多級反向代理的話,X-Forwarded-For的值并不止一個,而是一串IP地址,X-Forwarded-For中第一個非unknown的有效IP字符串,則為真實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);
}
// 使用代理,則獲取第一個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);
}
}
獲取請求工具類:
/**
* 獲取請求工具類
*/
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest(){
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}
以上就是Java項目常見工具類詳解的詳細內容,更多關于Java工具類的資料請關注腳本之家其它相關文章!
相關文章
SpringMVC 重定向參數(shù)RedirectAttributes實例
這篇文章主要介紹了SpringMVC 重定向參數(shù)RedirectAttributes實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
Java通過MyBatis框架對MySQL數(shù)據(jù)進行增刪查改的基本方法
MyBatis框架由Java的JDBC API進一步封裝而來,在操作數(shù)據(jù)庫方面效果拔群,接下來我們就一起來看看Java通過MyBatis框架對MySQL數(shù)據(jù)進行增刪查改的基本方法:2016-06-06
MyBatis處理mysql主鍵自動增長出現(xiàn)的不連續(xù)問題解決
本文主要介紹了MyBatis處理mysql主鍵自動增長出現(xiàn)的不連續(xù)問題解決,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
使用Spring Boot搭建Java web項目及開發(fā)過程圖文詳解
這篇文章主要介紹了使用Spring Boot搭建Java web項目及開發(fā)過程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
Spring Cache和EhCache實現(xiàn)緩存管理方式
這篇文章主要介紹了Spring Cache和EhCache實現(xiàn)緩存管理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

