Util工具类(JwtUtil、MD5Util、ThreadLocalUtil、拦截器配置)

utils.JwtUtil

package com.lin.springboot01.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import java.util.Date;
import java.util.Map;

public class JwtUtil {
    private static final String KEY = "liner2332";
    //接受业务数据,生成token并返回
    public static String genToken(Map claims) {
        return JWT.create()
                    .withClaim("claims",claims)
                    .withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60*12))
                    .sign(Algorithm.HMAC256(KEY));
    }
    //接收token,验证token,并返回业务数据
    public static Map parseToken(String token){
        return JWT.require(Algorithm.HMAC256(KEY))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }
}

utils.MD5Util

package com.lin.springboot01.utils;

import java.security.MessageDigest;
 
import lombok.extern.slf4j.Slf4j;
 
@Slf4j
public class MD5Util {
 
 
    /***
     * MD5加码 生成32位md5码
     */
    public static String string2MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            log.info(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
	 
        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
 
    }
 
    /**
     * 加密解密算法 执行一次加密,两次解密
     */
    public static String convertMD5(String inStr) {
 
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;
 
    }
    
    /**
     * 判断输入的密码和数据库中保存的MD5密码是否一致
     * @param inputPassword 输入的密码
     * @param md5DB 数据库保存的密码
     * @return
     */
    public static boolean passwordIsTrue(String inputPassword,String md5DB) {
    	
    	String md5 = string2MD5(inputPassword);
    	return md5DB.equals(md5);
    }
    
 
    // 测试主函数
    public static void main(String args[]) {
        String s = new String("123456");
        log.info("原始:" + s);
        log.info("MD5后:" + string2MD5(s));
        log.info("密码是否一致:" + passwordIsTrue("123456","e10adc3949ba59abbe56e057f20f883e"));
 
    }
 
}

utils.ThreadLocalUtil

package com.lin.springboot01.utils;

public class ThreadLocalUtil {
    //提供ThreadLocal对象
    private static final ThreadLocal THREAD_LOCAL = new ThreadLocal();

    //根据键获取值
    public static  T get(){
        return (T) THREAD_LOCAL.get();
    }

    //存储键值对
    public static void set(Object value){
        THREAD_LOCAL.set(value);
    }

    //清除Threadlocal 防止内存泄露
    public static void remove(){
        THREAD_LOCAL.remove();
    }
}


pojo.Result

package com.lin.springboot01.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Result {
    private Integer code; //业务状态码 0-成功 1-失败
    private String message; //提示信息
    private T data; //相应数据

    //快速返回操作成功相应结果(带相应数据)
    public static  Result success(E data){
        return new Result<>(0,"操作成功",data);
    }
    public static Result success(){
        return new Result(0,"操作成功",null);
    }
    public static Result error(String message){
        return new Result(1,message,null);
    }

}

exception.GlobalExceptionHandler(参数校验失败异常处理,全局异常处理器)

package com.lin.springboot01.exception;

import com.lin.springboot01.pojo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在 被 @RequestMapping 注解的方法上。
@RestControllerAdvice
//参数校验失败异常处理,全局异常处理器
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result handleExcpetion(Exception e){
        e.printStackTrace();
        return Result.error(StringUtils.hasLength(e.getMessage())?e.getMessage():"操作失败");
    }
}

 

拦截器:

interceptors.LoginInterceptor(注册拦截器)

package com.lin.springboot01.interceptors;

import com.lin.springboot01.utils.JwtUtil;
import com.lin.springboot01.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            //能否解析成功
            Map claims = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        } catch (Exception e) {
            //解析失败,httpServletResponse响应码设置为401
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空Threadlocal中的数据
        ThreadLocalUtil.remove();
    }
}

config.WebConfig(config中配置拦截器)

package com.lin.springboot01.config;

import com.lin.springboot01.interceptors.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //登录接口和注册接口不拦截
        registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login","/user/register");
    }
}

      

你可能感兴趣的:(springboot+vue,python,前端,开发语言)