您的位置 首页 java

「软帝学院」:2019java五大常用工具类整理

1. json 转换工具

1. package com.taotao.utils;

3. import java.util.List;

5. import com.fasterxml.jackson.core.JsonProcessingException; 6. import com.fasterxml.jackson.databind.JavaType; 7. import com.fasterxml.jackson.databind.JsonNode; 8. import com.fasterxml.jackson.databind.ObjectMapper;

10. /**

11. * json转换工具类

12. */ 13. public class JsonUtils {

15. // 定义jackson对象 16. private static final ObjectMapper MAPPER = new ObjectMapper();

18. /**

19. * 将对象转换成json字符串。

20. * <p>Title: pojoToJson</p>

21. * <p>Description: </p>

22. * @param data

23. * @return

24. */ 25. public static String objectToJson(Object data) { 26. try { 27. String string = MAPPER.writeValueAsString(data); 28. return string; 29. } catch (JsonProcessingException e) { 30. e.printStackTrace(); 31. } 32. return null; 33. }

35. /**

36. * 将json结果集转化为对象

37. *

38. * @param jsonData json数据

39. * @param clazz 对象中的object类型

40. * @return

41. */ 42. public static <T> T jsonToPojo(String jsonData, Class<T> beanType) { 43. try { 44. T t = MAPPER.readValue(jsonData, beanType); 45. return t; 46. } catch (Exception e) { 47. e.printStackTrace(); 48. } 49. return null; 50. }

52. /**

53. * 将json数据转换成pojo对象list

54. * <p>Title: jsonToList</p>

55. * <p>Descript io n: </p>

56. * @param jsonData

57. * @param beanType

58. * @return

59. */ 60. public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) { 61. Java Type javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType); 62. try { 63. List<T> list = MAPPER.readValue(jsonData, javaType); 64. return list; 65. } catch (Exception e) { 66. e.printStackTrace(); 67. }

69. return null; 70. }

72. }

2. Cookie 的读写

1. package com.taotao.common.utils;

3. import java.io.UnsupportedEncodingException; 4. import java.net.URLDecoder; 5. import java.net.URLEncoder;

7. import javax.servlet.http.Cookie; 8. import javax.servlet.http.HttpServlet request ; 9. import javax.servlet.http.HttpServletResponse;

12. /**

13. *

14. * Cookie 工具类

15. *

16. */ 17. public final class CookieUtils {

19. /**

20. * 得到Cookie的值, 不编码

21. *

22. * @param request

23. * @param cookieName

24. * @return

25. */ 26. public static String getCookieValue(HttpServletRequest request, String cookieName) { 27. return getCookieValue(request, cookieName, false); 28. }

30. /**

31. * 得到Cookie的值,

32. *

33. * @param request

34. * @param cookieName

35. * @return

36. */ 37. public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) { 38. Cookie[] cookieList = request.getCookies(); 39. if (cookieList == null || cookieName == null) { 40. return null; 41. } 42. String retValue = null; 43. try { 44. for (int i = 0; i < cookieList.length; i++) { 45. if (cookieList[i].getName().equals(cookieName)) { 46. if (isDecoder) { 47. retValue = URLDecoder.decode(cookieList[i].getValue(), “UTF-8”); 48. } else { 49. retValue = cookieList[i].getValue(); 50. } 51. break; 52. } 53. } 54. } catch (UnsupportedEncodingException e) { 55. e.printStackTrace(); 56. } 57. return retValue; 58. }

60. /**

61. * 得到Cookie的值,

62. *

63. * @param request

64. * @param cookieName

65. * @return

66. */ 67. public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) { 68. Cookie[] cookieList = request.getCookies(); 69. if (cookieList == null || cookieName == null) { 70. return null; 71. } 72. String retValue = null; 73. try { 74. for (int i = 0; i < cookieList.length; i++) { 75. if (cookieList[i].getName().equals(cookieName)) { 76. retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString); 77. break; 78. } 79. } 80. } catch (UnsupportedEncodingException e) { 81. e.printStackTrace(); 82. } 83. return retValue; 84. }

86. /**

87. * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码

88. */ 89. public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, 90. String cookieValue) { 91. setCookie(request, response, cookieName, cookieValue, -1); 92. }

94. /**

95. * 设置Cookie的值 在指定时间内生效,但不编码

96. */ 97. public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, 98. String cookieValue, int cookieMaxage) { 99. setCookie(request, response, cookieName, cookieValue, cookieMaxage, false); 100. }

102. /**

103. * 设置Cookie的值 不设置生效时间,但编码

104. */ 105. public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, 106. String cookieValue, boolean isEncode) { 107. setCookie(request, response, cookieName, cookieValue, -1, isEncode); 108. }

110. /**

111. * 设置Cookie的值 在指定时间内生效, 编码参数

112. */ 113. public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, 114. String cookieValue, int cookieMaxage, boolean isEncode) { 115. doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode); 116. }

118. /**

119. * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)

120. */ 121. public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, 122. String cookieValue, int cookieMaxage, String encodeString) { 123. doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString); 124. }

126. /**

127. * 删除Cookie带cookie域名

128. */ 129. public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, 130. String cookieName) { 131. doSetCookie(request, response, cookieName, “”, -1, false); 132. }

134. /**

135. * 设置Cookie的值,并使其在指定时间内生效

136. *

137. * @param cookieMaxage cookie生效的最大秒数

138. */ 139. private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, 140. String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) { 141. try { 142. if (cookieValue == null) { 143. cookieValue = “”; 144. } else if (isEncode) { 145. cookieValue = URLEncoder.encode(cookieValue, “utf-8″); 146. } 147. Cookie cookie = new Cookie(cookieName, cookieValue); 148. if (cookieMaxage > 0) 149. cookie.setMaxAge(cookieMaxage); 150. if (null != request) {// 设置域名的cookie 151. String domainName = getDomainName(request); 152. System.out.println(domainName); 153. if (!”localhost”.equals(domainName)) { 154. cookie.setDomain(domainName); 155. } 156. } 157. cookie.setPath(“/”); 158. response.addCookie(cookie); 159. } catch (Exception e) { 160. e.printStackTrace(); 161. } 162. }

164. /**

165. * 设置Cookie的值,并使其在指定时间内生效

166. *

167. * @param cookieMaxage cookie生效的最大秒数

168. */ 169. private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, 170. String cookieName, String cookieValue, int cookieMaxage, String encodeString) { 171. try { 172. if (cookieValue == null) { 173. cookieValue = “”; 174. } else { 175. cookieValue = URLEncoder.encode(cookieValue, encodeString); 176. } 177. Cookie cookie = new Cookie(cookieName, cookieValue); 178. if (cookieMaxage > 0) 179. cookie.setMaxAge(cookieMaxage); 180. if (null != request) {// 设置域名的cookie 181. String domainName = getDomainName(request); 182. System.out.println(domainName); 183. if (!”localhost”.equals(domainName)) { 184. cookie.setDomain(domainName); 185. } 186. } 187. cookie.setPath(“/”); 188. response.addCookie(cookie); 189. } catch (Exception e) { 190. e.printStackTrace(); 191. } 192. }

194. /**

195. * 得到cookie的域名

196. */ 197. private static final String getDomainName(HttpServletRequest request) { 198. String domainName = null;

200. String serverName = request.getRequestURL(). toString (); 201. if (serverName == null || serverName.equals(“”)) { 202. domainName = “”; 203. } else { 204. serverName = serverName.toLowerCase(); 205. serverName = serverName.substring(7); 206. final int end = serverName.indexOf(“/”); 207. serverName = serverName.substring(0, end); 208. final String[] domains = serverName.split(“\\.”); 209. int len = domains.length; 210. if (len > 3) { 211. // www.xxx.com.cn 212. domainName = “.” + domains[len – 3] + “.” + domains[len – 2] + “.” + domains[len – 1]; 213. } else if (len <= 3 && len > 1) { 214. // xxx.com or xxx.cn 215. domainName = “.” + domains[len – 2] + “.” + domains[len – 1]; 216. } else { 217. domainName = serverName; 218. } 219. }

221. if (domainName != null && domainName.indexOf(“:”) > 0) { 222. String[] ary = domainName.split(“\\:”); 223. domainName = ary[0]; 224. } 225. return domainName; 226. }

228. }

3.HttpClientUtil

1. package com.taotao.utils;

3. import java.io.IOException; 4. import java.net.URI; 5. import java.util.ArrayList; 6. import java.util.List; 7. import java.util.Map;

9. import org.apache.http.NameValuePair; 10. import org.apache.http.client.entity.UrlEncodedFormEntity; 11. import org.apache.http.client.methods. close ableHttpResponse; 12. import org.apache.http.client.methods.HttpGet; 13. import org.apache.http.client.methods.HttpPost; 14. import org.apache.http.client.utils.URIBuilder; 15. import org.apache.http.entity.ContentType; 16. import org.apache.http.entity.StringEntity; 17. import org.apache.http.impl.client.CloseableHttpClient; 18. import org.apache.http.impl.client.HttpClients; 19. import org.apache.http.message.BasicNameValuePair; 20. import org.apache.http.util.EntityUtils;

22. public class HttpClientUtil {

24. public static String doGet(String url, Map<String, String> param) {

26. // 创建Httpclient对象 27. CloseableHttpClient httpclient = HttpClients.createDefault();

29. String resultString = “”; 30. CloseableHttpResponse response = null; 31. try { 32. // 创建uri 33. URIBuilder builder = new URIBuilder(url); 34. if (param != null) { 35. for (String key : param.keySet()) { 36. builder.addParameter(key, param.get(key)); 37. } 38. } 39. URI uri = builder.build();

41. // 创建http GET请求 42. HttpGet httpGet = new HttpGet(uri);

44. // 执行请求 45. response = httpclient.execute(httpGet); 46. // 判断返回状态是否为200 47. if (response.getStatusLine().getStatusCode() == 200) { 48. resultString = EntityUtils.toString(response.getEntity(), “UTF-8”); 49. } 50. } catch (Exception e) { 51. e.printStackTrace(); 52. } finally { 53. try { 54. if (response != null) { 55. response.close(); 56. } 57. httpclient.close(); 58. } catch (IOException e) { 59. e.printStackTrace(); 60. } 61. } 62. return resultString; 63. }

65. public static String doGet(String url) { 66. return doGet(url, null); 67. }

69. public static String doPost(String url, Map<String, String> param) { 70. // 创建Httpclient对象 71. CloseableHttpClient httpClient = HttpClients.createDefault(); 72. CloseableHttpResponse response = null; 73. String resultString = “”; 74. try { 75. // 创建Http Post请求 76. HttpPost httpPost = new HttpPost(url); 77. // 创建参数列表 78. if (param != null) { 79. List<NameValuePair> paramList = new ArrayList<>(); 80. for (String key : param.keySet()) { 81. paramList.add(new BasicNameValuePair(key, param.get(key))); 82. } 83. // 模拟表单 84. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); 85. httpPost.setEntity(entity); 86. } 87. // 执行http请求 88. response = httpClient.execute(httpPost); 89. resultString = EntityUtils.toString(response.getEntity(), “utf-8”); 90. } catch (Exception e) { 91. e.printStackTrace(); 92. } finally { 93. try { 94. response.close(); 95. } catch (IOException e) { 96. // TODO Auto-generated catch block 97. e.printStackTrace(); 98. } 99. }

101. return resultString; 102. }

104. public static String doPost(String url) { 105. return doPost(url, null); 106. }

108. public static String doPostJson(String url, String json) { 109. // 创建Httpclient对象 110. CloseableHttpClient httpClient = HttpClients.createDefault(); 111. CloseableHttpResponse response = null; 112. String resultString = “”; 113. try { 114. // 创建Http Post请求 115. HttpPost httpPost = new HttpPost(url); 116. // 创建请求内容 117. StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); 118. httpPost.setEntity(entity); 119. // 执行http请求 120. response = httpClient.execute(httpPost); 121. resultString = EntityUtils.toString(response.getEntity(), “utf-8”); 122. } catch (Exception e) { 123. e.printStackTrace(); 124. } finally { 125. try { 126. response.close(); 127. } catch (IOException e) { 128. // TODO Auto-generated catch block 129. e.printStackTrace(); 130. } 131. }

133. return resultString; 134. } 135. }

4.FastDFSClient工具类

1. package cn.itcast.fastdfs.cliennt;

3. import org.csource.common.NameValuePair; 4. import org.csource.fastdfs.ClientGlobal; 5. import org.csource.fastdfs.StorageClient1; 6. import org.csource.fastdfs.StorageServer; 7. import org.csource.fastdfs.TrackerClient; 8. import org.csource.fastdfs.TrackerServer;

10. public class FastDFSClient {

12. private TrackerClient trackerClient = null; 13. private TrackerServer trackerServer = null; 14. private StorageServer storageServer = null; 15. private StorageClient1 storageClient = null;

17. public FastDFSClient(String conf) throws Exception { 18. if (conf.contains(“classpath:”)) { 19. conf = conf.replace(“classpath:”, this.getClass().getResource(“/”).getPath()); 20. } 21. ClientGlobal.init(conf); 22. trackerClient = new TrackerClient(); 23. trackerServer = trackerClient.getConnection(); 24. storageServer = null; 25. storageClient = new StorageClient1(trackerServer, storageServer); 26. }

28. /**

29. * 上传文件方法

30. * <p>Title: uploadFile</p>

31. * <p>Description: </p>

32. * @param fileName 文件全路径

33. * @param extName 文件扩展名,不包含(.)

34. * @param metas 文件扩展信息

35. * @return

36. * @throws Exception

37. */ 38. public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception { 39. String result = storageClient.upload_file1(fileName, extName, metas); 40. return result; 41. }

43. public String uploadFile(String fileName) throws Exception { 44. return uploadFile(fileName, null, null); 45. }

47. public String uploadFile(String fileName, String extName) throws Exception { 48. return uploadFile(fileName, extName, null); 49. }

51. /**

52. * 上传文件方法

53. * <p>Title: uploadFile</p>

54. * <p>Description: </p>

55. * @param fileContent 文件的内容,字节数组

56. * @param extName 文件扩展名

57. * @param metas 文件扩展信息

58. * @return

59. * @throws Exception

60. */ 61. public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {

63. String result = storageClient.upload_file1(fileContent, extName, metas); 64. return result; 65. }

67. public String uploadFile(byte[] fileContent) throws Exception { 68. return uploadFile(fileContent, null, null); 69. }

71. public String uploadFile(byte[] fileContent, String extName) throws Exception { 72. return uploadFile(fileContent, extName, null); 73. } 74. }

1. <span style=”font-size:14px;font-weight:normal;”>public class FastDFSTest {

3. @Test 4. public void testFileUpload() throws Exception { 5. // 1、加载配置文件,配置文件中的内容就是tracker服务的地址。 6. ClientGlobal.init(“D:/workspaces-itcast/term197/taotao-manager-web/src/main/resources/resource/client.conf”); 7. // 2、创建一个TrackerClient对象。直接new一个。 8. TrackerClient trackerClient = new TrackerClient(); 9. // 3、使用TrackerClient对象创建连接,获得一个TrackerServer对象。 10. TrackerServer trackerServer = trackerClient.getConnection(); 11. // 4、创建一个StorageServer的引用,值为null 12. StorageServer storageServer = null; 13. // 5、创建一个StorageClient对象,需要两个参数TrackerServer对象、StorageServer的引用 14. StorageClient storageClient = new StorageClient(trackerServer, storageServer); 15. // 6、使用StorageClient对象上传图片。 16. //扩展名不带“.” 17. String[] strings = storageClient.upload_file(“D:/Documents/Pictures/images/200811281555127886.jpg”, “jpg”, null); 18. // 7、返回数组。包含组名和图片的路径。 19. for (String string : strings) { 20. System.out.println(string); 21. } 22. } 23. }</span>

# ![image](

5.获取异常的堆栈信息

1. package com.taotao.utils;

3. import java.io.PrintWriter; 4. import java.io.StringWriter;

6. public class ExceptionUtil {

8. /**

9. * 获取异常的堆栈信息

10. *

11. * @param t

12. * @return

13. */ 14. public static String getStackTrace(Throwable t) { 15. StringWriter sw = new StringWriter(); 16. PrintWriter pw = new PrintWriter(sw);

18. try { 19. t.printStackTrace(pw); 20. return sw.toString(); 21. } finally { 22. pw.close(); 23. } 24. } 25. }

最后,开发这么多年我也总结了一套学习Java的资料,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。

文章来源:智云一二三科技

文章标题:「软帝学院」:2019java五大常用工具类整理

文章地址:https://www.zhihuclub.com/171137.shtml

关于作者: 智云科技

热门文章

网站地图