Java常用Utils工具类

1.发送邮件类,在jdk8更新以后,以前的发送邮件类无法使用,会报错,下面的邮件工具类经过修改完美运行,依赖如下:

 <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-email</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.8.10</version>
    </dependency>

import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import java.util.Properties;

@Slf4j
public class EmailUtil {
    //邮件服务器主机名
    // QQ邮箱的 SMTP 服务器地址为: smtp.qq.com
    private static String myEmailSMTPHost = "smtp.qq.com";

    //发件人邮箱
    private static String myEmailAccount = "***@qq.com";

    //发件人邮箱密码(授权码)
    //在开启SMTP服务时会获取到一个授权码,把授权码填在这里
    private static String myEmailPassword = "*****";

    /**
     * 邮件单发(自由编辑短信,并发送,适用于私信)
     *
     * @param email 收件箱地址

     * @throws Exception
     */

    public static String sendEmail(String email,String title,String detail) {
        Transport ts = null;
        try {


            Properties prop = new Properties();
            //设置QQ邮件服务器
            prop.setProperty("mail.host", "smtp.qq.com");
            //邮件发送协议
            prop.setProperty("mail.transport.protocol", "smtp");
            //需要验证用户名密码
            prop.setProperty("mail.smtp.auth", "true");

            //使用JavaMail发送邮件的5个步骤
            //1.创建定义整个应用程序所需的环境信息的Session对象
            Session session = Session.getDefaultInstance(prop, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    //发件人邮件用户名、授权码
                    return new PasswordAuthentication(myEmailAccount,
                            myEmailPassword);
                }
            });

            //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
            session.setDebug(false);

            //2、通过session得到transport对象
            ts = session.getTransport();

            //3、使用邮箱的用户名和授权码连上邮件服务器
            ts.connect("smtp.qq.com",myEmailAccount, myEmailPassword);

            //4,创建邮件
            //4-1.txt,创建邮件对象
            MimeMessage message = new MimeMessage(session);

            //4-2,指明邮件的发件人
            message.setFrom(new InternetAddress(myEmailAccount));

            //4-3,指明邮件的收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));

            //4-4,邮件标题
            message.setSubject(title);

            //4-5,邮件文本内容
            message.setContent(detail,"text/html;charset=UTF-8");

            //4-6,发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            //5,关闭连接
            ts.close();

        } catch (Exception e) {
           return "发送邮件失败";
        }
        return "发送成功";
    }

}

2.JWT工具类

    <!--jwt依赖包-->
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.4.0</version>
    </dependency>

import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;


public class JWT {
    // 任意字符串
    private static final String SING = "xxxx@Jerry";

    private static String token;

    // get and set
    public static String getToken() {
        return token;
    }
    public static void setToken(String token) {
        JWT.token = token;
    }

    // 生成用户token
    public static String getJWToken(Integer id){

        Calendar instance = Calendar.getInstance();
        // 设置过期时间,这里设置的是30天
        instance.add(Calendar.DATE,30);

        JWTCreator.Builder builder = com.auth0.jwt.JWT.create();

        // 指定标识字段
        builder.withClaim("userid", id);

        // 指定过期时间
        token = builder.withExpiresAt(instance.getTime())
                // 指定生成算法及签名
                .sign(Algorithm.HMAC256(SING));

        return token;
    }

    // 验证token,返回true或false
    public static boolean verify(String token){
        try {
            com.auth0.jwt.JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    // 验证token,正确通过,否则抛出异常
    public static DecodedJWT verifyToken(String lawyerToken){
        return com.auth0.jwt.JWT.require(Algorithm.HMAC256(SING)).build().verify(lawyerToken);
    }

    // 从token中获取用户id
    public static int getTokenId(String token){
        DecodedJWT verify = com.auth0.jwt.JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        return verify.getClaim("userid").asInt();
    }
}

如何使用jwt进行token验证呢,在项目目录中创建一个config文件夹

添加WebMvcConfig文件和UserInterceptor文件

WebMvcConfig文件如下:


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 用户拦截器
        registry.addInterceptor(new com.yzdx.AiInterviewer.config.UserInterceptor())
                // 需要拦截的请求
                .addPathPatterns("/**")
                // 需要放行的请求
                .excludePathPatterns("/admin/login");
    }
}

UserInterceptor文件如下:

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.yzdx.AiInterviewer.utiles.JWT;
import net.minidev.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


public class UserInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();

        String Token = request.getHeader("Authorization");;

        // 捕获刚刚JWT中抛出的异常,并封装对应的返回信息
        try {
            JWT.verifyToken(Token);
            return true;
        }catch (SignatureVerificationException e){
            map.put("msg", "无效签名");
        }catch (TokenExpiredException e){
            map.put("msg", "已过期");
        }catch (AlgorithmMismatchException e){
            map.put("msg", "算法不一致");
        }catch (Exception e){
            map.put("msg", "无效身份信息");
        }
        // 封装返回值
        map.put("code", 401);
        JSONObject json = new JSONObject(map);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.print(json);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            writer.close();
        }
        return false;
    }
}

3.MD5工具类

import org.springframework.util.DigestUtils;

import java.util.UUID;

public class MD5Util {

    public static String getSalt(){
        String salt= UUID.randomUUID().toString().toUpperCase();

        return salt;
    }


    public static String GetMD5Password(String password, String salt){

        for (int i = 0; i < 3; i++) {

            password= DigestUtils.md5DigestAsHex((salt+password+salt).getBytes()).toUpperCase();

        }
        return password;
    }

}

MD5工具类我是和Randomcode工具类一起使用:


import java.util.Random;

public class RandomCodeUtil {
    /**
     * 生成的验证码
     * @param index 生成验证码的长度
     * @return
     */
    public static String random(Integer index){
        String code = "";
        Random rd=new Random();
        for (int i = 0; i < index; i++) {
            int r = rd.nextInt(10); //每次随机出一个数字(0-9)
            code = code + r;  //把每次随机出的数字拼在一起
        }
        System.out.println(code);
        return code;
    }
}

Time工具类


import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeUtil {

    public static String getTime(){
        Date now =new Date();

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");

          String time = simpleDateFormat.format(now);
          return time;
        }

        /**
         * 获取精确时间
         * */
    public static String getPreciseTime(){
        Date now =new Date();

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String time = simpleDateFormat.format(now);

        return time;
    }

}

SMS工具类(阿里云)

    <!--阿里云短信服务-->
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>4.5.16</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
        <version>2.1.0</version>
    </dependency>
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;

public class SMSUtils {
    /**
     * 发送短信
     * @param signName 签名
     * @param templateCode 模板
     * @param phoneNumbers 手机号
     * @param param 参数
     */
    public static void sendMessage(String signName, String templateCode,String phoneNumbers,String param){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "yourAccessKeyId", "yourSecret");
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setSysRegionId("cn-hangzhou");
        request.setPhoneNumbers(phoneNumbers);
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        request.setTemplateParam("{\"code\":\""+param+"\"}");
        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println("短信发送成功");
        }catch (ClientException e) {
            e.printStackTrace();
        }
    }

定时任务工具类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component // 把此类托管给 Spring,不能省略
public class TaskUtils {
 
    // 添加定时任务
    @Scheduled(cron = "0 0 0 * * ? ") // cron表达式:每天2:00 执行
    public void doTask(){
     //代码
        }

    }

}

使用时要在Appliaction中添加注释

@EnableScheduling似乎是这个忘得差不多了

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ᯤ⁶ᴳ⁺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值