Java项目常见工具类总结

Posted LL.LEBRON

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java项目常见工具类总结相关的知识,希望对你有一定的参考价值。

总结平时项目中使用的工具类🎯🎈🍭

Java项目常见工具类总结

JWT工具类

这里一共涉及四个方法:

  1. 传入用户信息获得token
  2. 传入token字符串判断token是否存在与有效
  3. 传入HttpServletRequest,通过获取Header中的token判断是否存在与有效
  4. 根据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")
                //设置签发时间
                .setIssuedAt(new Date())
                //设置过期时间=当前时间+过多久过期的时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //设置token主体部分,存储用户信息
                .claim("id", id)
                .claim("nickname", nickname)
                //设置签发算法+秘钥
                .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;
    

    /**
     * 根据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 
            //用来将字节转换成 16 进制表示的字符
            char hexChars[] = '0', '1', '2', '3', '4', '5', '6', '7', '8',
                    '9', 'a', 'b', 'c', 'd', 'e', 'f';
            byte[] bytes = strSrc.getBytes();
            //得到实现指定摘要算法的 MessageDigest对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            //使用指定的 byte数组更新摘要
            md.update(bytes);
            //通过执行诸如填充之类的最终操作完成哈希计算。在调用此方法之后,摘要被重置
            bytes = md.digest();
            int j = bytes.length;
            char[] chars = new char[j * 2];
            int k = 0;
            //从第一个字节开始,对每一个字节,转换成 16 进制字符
            for (int i = 0; i < bytes.length; i++) 
                //取第 i 个字节
                byte b = bytes[i];
                //取字节中高 4 位的数字转换
                chars[k++] = hexChars[b >>> 4 & 0xf];
                //取字节中低 4 位的数字转换
                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 
        //点播服务接入区域
        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;
    

日期操作工具类

这里一共涉及二个方法:

  1. 格式化Date日期,转换为字符串返回
  2. 在日期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 要加的天数,可能为负数
     */
    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,可以实现:

  1. 发送一个 Post 请求
  2. 提交form表单
  3. 发送一个 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);
    

    /**
    * 发送一个 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;
        //创建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);
            
            // 设置参数
            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")) 
                // 执行 Https 请求
                client = createSSLInsecureClient();
                res = client.execute(post);
             else 
                // 执行 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, 以上是关于Java项目常见工具类总结的主要内容,如果未能解决你的问题,请参考以下文章

JAVA 日期工具类的总结

solr分布式索引实战分片配置读取:工具类configUtil.java,读取配置代码片段,配置实例

java开发工具——Eclipse的常见使用说明

项目总结——java工具类

回归 | js实用代码片段的封装与总结(持续更新中...)

常用高效 Java 工具类总结