Web常用工具类

Cheryl

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

        <!-- Maps,Sets,Preconditions -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>28.1-jre</version>
        </dependency>
        <!-- CollectionUtils -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.4</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>

Json工具类

ServerResponse - 通用Json响应对象

ResponseCode是封装code和desc的枚举类

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

}

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

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

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

File2MultipartFileUtil - File转MultipartFile工具类

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

SendMailUtil - java发送邮件的工具包

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-非常强大的文件转字节数组工具包

阅读 1.2k

Java技术栈 [链接]

13 声望
0 粉丝
0 条评论

Java技术栈 [链接]

13 声望
0 粉丝
文章目录
宣传栏