人手必備的java工具類,中間件html
<!-- Maps,Sets,CollectionUtils --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>28.1-jre</version> </dependency> <!-- StringUtils --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <!-- JSON專用工具包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>
ResponseCode是封裝code和desc的枚舉類java
package com.mmall.common; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.map.annotate.JsonSerialize; import java.io.Serializable; /** * 表明響應裏要封裝的數據對象 * @param <T> */ // 設置返回的json對象沒有null,保證序列化json的時候,若是是null的對象,key也會消失 //@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)//jackson 實體轉json 爲NULL的字段不參加序列化(即不顯示) public class ServerResponse<T> implements Serializable { /** * 狀態碼 * */ private int status; /** * 響應的相關信息(例如用戶名不存,密碼錯誤等) */ private String msg; /** * 封裝的數據對象信息 */ private T data; // 構建私有構造器,封裝public方法時更加優雅 private ServerResponse(int status){ this.status = status; } private ServerResponse(int status,String msg){ this.status = status; this.msg = msg; } private ServerResponse(int status,String msg,T data){ this.status = status; this.msg = msg; this.data = data; } private ServerResponse(int status,T data){ this.status = status; this.data = data; } // 在序列化json對象過程當中忽視該結果 @JsonIgnore public boolean isSuccess(){ return this.status == ResponseCode.SUCCESS.getCode(); } public int getStatus() { return status; } public String getMsg() { return msg; } public T getData() { return data; } /** * 成功響應,靜態方法對外開放 */ public static <T> ServerResponse<T> createBySuccess(){ return new ServerResponse<T>(ResponseCode.SUCCESS.getCode()); } // 只響應成功信息 public static <T> ServerResponse<T> createBySuccessMessage(String msg){ return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg); } public static <T> ServerResponse<T> createBySuccess(T data){ return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data); } // 建立一個成功的服務器響應,把響應信息和對象data填充進去 public static <T> ServerResponse<T> createBySuccess(String msg,T data){ return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg, data); } /** * 失敗響應 */ public static <T> ServerResponse<T> createByError(){ return new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc()); } // 只響應失敗信息 public static <T> ServerResponse<T> createByErrorMessage(String errorMessage){ return new ServerResponse<T>(ResponseCode.ERROR.getCode(),errorMessage); } /** * 暴露一個參數端錯誤的響應 */ public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode,String errorMessage){ return new ServerResponse<T>(errorCode,errorMessage); } }
import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * @Title JsonUtils.java * @Package com.aust.utils * @Description 定義響應的Json對象格式,以及如何轉換爲Json對象 * Copyright:Copyright (c) 2019 * Company:anhui.aust.imooc * * @author austwuhong * @date 2019/10/31 19:11 PM * @version v1.0 */ public class JackSonUtils { private static final ObjectMapper MAPPER = new ObjectMapper(); /** * 將對象轉爲Json格式的字符串 * @param data * @return */ public static Object objectToJson(Object data) { try { String string = MAPPER.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } /** * 將Json結果集轉爲對象 * @param <T> * @param jsonData Json數據 * @param beanType 對象Object類型 * @return */ public static <T> T jsonToPojo(String jsonData,Class<T> beanType) { try { T t = MAPPER.readValue(jsonData, beanType); return t; } catch (JsonMappingException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; class User { private String username; private int userId; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getUserId() { return userId; } public void setUserId(byte userId) { this.userId = userId; } @Override public String toString() { return "User [username=" + username + ", userId=" + userId + "]"; } } /** * google的JSON工具類gson將普通的json串轉爲pojo對象 * @author Administrator * */ public class GSONUtil { /** * @param jsonData JSON格式的字符串 * @return JavaBean對象 */ public <T> T getJSON(String jsonData) { Gson gson = new Gson(); Type typeOfT = new TypeToken<T>(){}.getType(); T t = gson.fromJson(jsonData, typeOfT); return t; } // 基礎測試 public static void main(String[] args) { String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]"; jsonData = "{" + " \"code\":200," + " \"message\":\"success\"," + " \"data\":\"{\"username\":\"arthinking\",\"userId\":001}\"" + " }"; jsonData = "{\"username\":\"rachel\",\"userId\":123456}"; Gson gson = new Gson(); Type typeOfT = new TypeToken<User>(){}.getType(); User users = gson.fromJson(jsonData, typeOfT); System.out.println("解析JSON數據"); // for (Iterator<User> iterator = users.iterator(); iterator.hasNext();) { // User user = iterator.next(); // System.out.print(user.getUsername() + " | "); // System.out.println(user.getUserId()); // } System.out.println(users); } }
經過序列化和內存流對象流實現對象深拷貝
其實Spring也有一個用於複製bean的工具類mysql
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * 經過序列化和內存流對象流實現對象深拷貝 * @author Administrator * */ public class CloneUtils { // 禁止實例化 private CloneUtils() { throw new AssertionError(); } @SuppressWarnings("unchecked") public static <T> T clone(T obj) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bout); oos.writeObject(obj); // 輸入流必須肯定源 ByteArrayInputStream bis = new ByteArrayInputStream(bout.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); // NOTICE 強制從Object轉爲泛型T,若是傳入的對象類型不是T可能會出錯 return (T) ois.readObject(); } }
可用於SSM框架中文件的上傳web
import java.io.File; import java.io.IOException; import org.springframework.web.multipart.MultipartFile; public class UploadUtil { private static String basePath = "D:\\Repositories\\uploadFiles\\";// 文件上傳保存路徑 /** * 管理上傳文件的保存 * @param file * @return 若是保存上傳文件成功,則返回新文件名,不然返回空"" */ public static String saveFile(MultipartFile file) { try { // 爲防止文件名重複,須要使用隨機文件名+文件擴展名,但保存到數據庫時應使用原文件名(不可用時間戳,由於在多線程的狀況下有可能取到同一個時間戳) // 不使用UUID,UUID入庫性能並很差 String extName = file.getOriginalFilename(); int index = extName.lastIndexOf("."); if(index > -1) { extName = extName.substring(index);// 這裏substring中參數不能爲-1不然報異常 } else { extName = ""; } // 隨機名+後綴命名並保存到basePath路徑下 String newFileName = Math.random() + extName; File newFilePath = new File(basePath + newFileName); while(newFilePath.exists()) { newFileName = Math.random() + extName; newFilePath = new File(basePath + newFileName); } file.transferTo(newFilePath); return newFileName; } catch (IllegalStateException | IOException e) { e.printStackTrace(); } return ""; } }
節省jdbc鏈接代碼量算法
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * SELF 自定義工具類 * 標準的數據庫工具類 * @author Shiniad */ public class DBUtil { public static String username = "root"; public static String password = "root"; public static String driver = "com.mysql.jdbc.Driver"; public static String url = "jdbc:mysql://127.0.0.1:3306/mywork?useUnicode=true&characterEncoding=utf8"; static String sql = "insert into sys_user(uname,upassword) values ('測試',325) "; public static Connection conn = null; public static Statement st = null; public static ResultSet rs = null; // 增刪改 public static int update() { int count = 0; try { Class.forName(driver);// 加載驅動 conn = DriverManager.getConnection(url,username,password);// 建立鏈接 st = conn.createStatement();// 執行SQL語句 count = st.executeUpdate(sql); } catch(ClassNotFoundException e) { e.printStackTrace(); return 0; } catch(SQLException e) { e.printStackTrace(); return 0; } return count; } // 查詢 public static ResultSet query() { try { Class.forName(driver);// 加載驅動 conn = DriverManager.getConnection(url,username,password);// 建立鏈接 st = conn.createStatement();// 執行SQL語句 rs = st.executeQuery(sql); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } catch (SQLException e) { e.printStackTrace(); return null; } return rs; } // 關閉內部資源 public static void closeSource() { if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(st!=null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } // 關閉外部資源 public static void closeSource(ResultSet rs, Statement st, Connection conn) { if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(st!=null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* public static void main(String[] args) throws SQLException, ClassNotFoundException { DBUtil.sql = "select * from sys_user"; ResultSet rSet = DBUtil.query(); while(rSet.next()) { System.out.println(rSet.getInt(1) + "\t" + rSet.getString(2)); } // 數據庫的插入操做 // DBUtil.sql = "insert into sys_user(uname,upassword) values ('測試2',325) "; // if(DBUtil.update()>0) { // System.out.println("添加成功"); // } else { // System.out.println("添加失敗"); // } // 關閉鏈接(關閉內部鏈接) DBUtil.closeSource(); System.out.println(DBUtil.conn.isClosed()); } */ }
import java.security.SecureRandom; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; /** * * SELF 自定義工具類 * 經典DES加密 * @author 宏 */ public class DES { // 加密 public static String encrypt(String content, String password) { byte[] contentByte = content.getBytes(); byte[] passwordByte = password.getBytes(); SecureRandom random = new SecureRandom(); try { // 生成祕文證書 DESKeySpec key = new DESKeySpec(passwordByte); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = factory.generateSecret(key); // 使用證書加密 Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, random);// 配置參數 byte[] result = cipher.doFinal(contentByte); // Base64加密,將二進制文件轉成字符串格式 String contentResult = Base64.getEncoder().encodeToString(result); return contentResult; } catch(Exception e) { e.printStackTrace(); return null; } } // 解密 public static byte[] decrypt(String password, byte[] result) { byte[] passwordByte = password.getBytes(); SecureRandom random = new SecureRandom(); try { // 生成祕文證書 DESKeySpec key = new DESKeySpec(passwordByte); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = factory.generateSecret(key); // 解密 Cipher decipher = Cipher.getInstance("DES"); decipher.init(Cipher.DECRYPT_MODE, secretKey, random); byte[] de_result = decipher.doFinal(result); return de_result; } catch(Exception e) { e.printStackTrace(); return null; } } // 解密2 public static byte[] decrypt(String password, String contentResult) { byte[] passwordByte = password.getBytes(); byte[] result = Base64.getDecoder().decode(contentResult); SecureRandom random = new SecureRandom(); try { // 生成祕文證書 DESKeySpec key = new DESKeySpec(passwordByte); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = factory.generateSecret(key); // 解密 Cipher decipher = Cipher.getInstance("DES"); decipher.init(Cipher.DECRYPT_MODE, secretKey, random); byte[] de_result = decipher.doFinal(result); return de_result; } catch(Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) throws Exception { String content = "123456"; String password = "UnkonwnSecret";// 明文密碼 String contentResult = encrypt(content, password); System.out.println("加密後的文本:" + contentResult); if(contentResult!=null) { byte[] myByte = decrypt(password, contentResult); System.out.println("解密後的文本:" + new String(myByte)); } // // 生成祕文證書 // DESKeySpec key = new DESKeySpec(password.getBytes()); // SecretKeyFactory factory = SecretKeyFactory.getInstance("DES"); // SecretKey secretKey = factory.generateSecret(key);// 將明文密碼轉爲祕鑰證書 // // 使用證書加密 // Cipher cipher = Cipher.getInstance("DES"); // cipher.init(Cipher.ENCRYPT_MODE, secretKey); // byte[] result = cipher.doFinal(content.getBytes()); // // Base64轉碼 // String base64Result = Base64.getEncoder().encodeToString(result); } }
SHA1同理,將MD5換成SHA1便可spring
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** * SELF 自定義類 * 加密算法 MD5/SHA1 * @author Shiniad * */ public class MD5 { public static String contentResult; public static String salt; public static void encrypt(String password) { MD5.contentResult = null; MD5.salt = null; SecureRandom random = new SecureRandom(); String salt = String.valueOf(random.nextDouble());// 隨機鹽 String contentResult = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] result = md.digest((password).getBytes()); contentResult = ByteArrayUtil.bytesToHex(result); if(contentResult!=null && salt!=null) { MD5.contentResult = contentResult; MD5.salt = salt; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } public static boolean verification(String salt,String secretKey) { System.out.print("請輸入密碼驗證:"); java.util.Scanner in = new java.util.Scanner(System.in); String password = in.nextLine(); try { MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] result = md.digest((password+salt).getBytes()); String contentResult = ByteArrayUtil.bytesToHex(result); if(contentResult.equals(secretKey)) { System.out.println("您輸入的密碼正確。"); in.close(); return true; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } System.out.println("您輸入的密碼錯誤!"); in.close(); return false; } // 基礎測試 public static void main(String[] args) throws Exception { String password = "123456"; encrypt(password); System.out.println("鹽值爲:" + MD5.salt + ", 密鑰爲:" + MD5.contentResult); while( !MD5.verification(MD5.salt, MD5.contentResult) ) { MD5.verification(MD5.salt, MD5.contentResult); } // MD5的核心API // MessageDigest md = MessageDigest.getInstance("MD5"); // byte[] result = md.digest(password.getBytes()); } }
/** * SELF 自定義工具類 * 字節轉換工具,將字節/字節數組轉爲16進制數(字符串格式) * @author 宏 */ public class ByteArrayUtil { public static String byteToHex(byte b) { String hex = Integer.toHexString(b & 0xFF);// 將b與常數(1111 1111)sub2進行與運算,將頭三個字節的隨機位的值定爲0 if(hex.length() < 2) { hex = "0" + hex;// 標記個位整數爲16進制數 } return hex; } public static String bytesToHex(byte[] b) { StringBuffer sb = new StringBuffer(); String str = ""; for (byte c : b) { str = byteToHex(c); sb.append(str); } return new String(sb); } }
public class File2MultipartFileUtil{ public static MultipartFile getMultipartFile(String filePath) { File file = new File(filePath); FileItemFactory factory = new DiskFileItemFactory(16, null); FileItem item = factory.createItem(file.getName(), "text/plain", true, file.getName()); int bytesRead = 0; byte[] buffer = new byte[4096]; try(FileInputStream fis = new FileInputStream(file); OutputStream os = item.getOutputStream()) { while((bytesRead=fis.read(buffer, 0, 4096)) != -1) { os.write(buffer, 0, bytesRead); } } catch (Exception e) { throw new RuntimeException("getMultipartFile error:" + e.getMessage()); } MultipartFile cFilePath = new CommonsMultipartFile(item); return cFilePath; } }
package com.mydemo.project.utils; import java.io.UnsupportedEncodingException; import java.security.Security; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SendMailUtil { private static final Logger logger = LoggerFactory.getLogger(SendMailUtil.class); /** * * @param subject 郵件主題 * @param content 郵件內容(能夠是html) * @param toEmailAddres 收件人 * @param log * @throws MessagingException */ @SuppressWarnings("restriction") public static void sendMail(String subject,String content,String toEmailAddres) throws MessagingException { String host = "smtp.163.com"; //郵箱服務器地址 String port = "465"; //發送郵件的端口 25/587 String auth = "true"; //是否須要進行身份驗證,視調用的郵箱而定,比方說QQ郵箱就須要,不然就會發送失敗 String protocol = "smtp"; //傳輸協議 String mailFrom = "1*5@163.com"; //發件人郵箱 String personalName = "1*5"; //發件人郵箱別名 String username = "1*5@163.com"; //發件人郵箱用戶名 String password = "***"; //發件人郵箱密碼,163郵箱使用受權碼 String mailDebug = "false"; //是否開啓debug String contentType = null; //郵件正文類型 Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); // ssl認證 final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", auth == null ? "true" : auth); props.put("mail.transport.protocol", protocol == null ? "smtp" : protocol); props.put("mail.smtp.port", port == null ? "25" : port); props.put("mail.debug", mailDebug == null ? "false" : mailDebug); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); Session mailSession = Session.getInstance(props); // 設置session,和郵件服務器進行通信。 MimeMessage message = new MimeMessage(mailSession); // 設置郵件主題 message.setSubject(subject); // 設置郵件正文 message.setContent(content, contentType == null ? "text/html;charset=UTF-8" : contentType); // 設置郵件發送日期 message.setSentDate(new Date()); InternetAddress address = null; try { address = new InternetAddress(mailFrom, personalName); } catch (UnsupportedEncodingException e) { logger.info("ip地址編碼異常:{}",e.getMessage()); e.printStackTrace(); } // 設置郵件發送者的地址 message.setFrom(address); // 設置郵件接收方的地址 message.setRecipients(Message.RecipientType.TO, toEmailAddres); Transport transport = null; transport = mailSession.getTransport(); message.saveChanges(); transport.connect(host, username, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } public static void main(String[] args) { String subject = "from java"; String content = "<h1>hello world!</h1>"; String toEmailAddres = "7*@qq.com"; try { sendMail(subject, content, toEmailAddres); System.out.println("郵件發送成功"); } catch (MessagingException e) { logger.info("郵件發送失敗:{}",e.getMessage()); e.printStackTrace(); } } }
其它參考網址
https://www.jianshu.com/p/d36...
經常使用guava工具包
比較經常使用的有Preconditions前置校驗/Lists/Maps工具類
https://www.baidu.com/link?ur...
https://blog.csdn.net/Munger6...
commons-io工具包
FileUtils-很是強大的文件轉字節數組工具包sql