Web常用工具类

人手必备的java工具类,中间件

Json工具类

JackSonUtils - Json与pojo对象相互转化工具类

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 
     * @param jsonData    Json数据
     * @param beanType 对象Object类型
     * @return
     */
    public static  T jsonToPojo(String jsonData,Class 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;
    }
    
}

GSONUtil - google的JSON工具类gson将普通的json串转为pojo对象

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 getJSON(String jsonData) {
        Gson gson = new Gson();
        Type typeOfT = new TypeToken(){}.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(){}.getType();
        User users = gson.fromJson(jsonData, typeOfT);
        
        System.out.println("解析JSON数据");
//        for (Iterator iterator = users.iterator(); iterator.hasNext();) {
//            User user = iterator.next();
//            System.out.print(user.getUsername() + " | ");
//            System.out.println(user.getUserId());
//        }
        System.out.println(users);
    }
}

CloneUtils - 对象克隆工具类

通过序列化和内存流对象流实现对象深拷贝
其实Spring也有一个用于复制bean的工具类

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 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();
    }
}

UploadUtil - 文件上传工具类

可用于SSM框架中文件的上传

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 "";
    }

}

DBUtil - JDBC连接专用工具类

节省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());
    }
    */
}

加密工具类

DES - DES加密工具类

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);
    }

}

MD5 - MD5加密工具类

SHA1同理,将MD5换成SHA1即可

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());
    }
}

ByteArrayUtil - 字节转换工具类,将字节/字节数组转为16进制数(字符串格式)

/**
 * 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);
    }
}

其它参考网址
https://www.jianshu.com/p/d36...
常用guava工具包
比较常用的有Preconditions前置校验/Lists/Maps工具类
https://www.baidu.com/link?ur...
https://blog.csdn.net/Munger6...
commons-io工具包
FileUtils-非常强大的文件转字节数组工具包

你可能感兴趣的:(eclipse,java)