import com.yyf.blogapi.po.SysUser;
public class UserThreadLocal {
private UserThreadLocal() {
}
private static final ThreadLocal<SysUser> LOCAL = new ThreadLocal<>();
public static void put(SysUser sysUser) {
LOCAL.set(sysUser);
}
public static SysUser get() {
return LOCAL.get();
}
public static void remove() {
LOCAL.remove();
}
}
package com.yyf.blogapi.handler;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yyf.blogapi.po.SysUser;
import com.yyf.blogapi.service.ISysUserService;
import com.yyf.blogapi.util.JwtUtil;
import com.yyf.blogapi.util.UserThreadLocal;
import com.yyf.blogapi.vo.ErrorCode;
import com.yyf.blogapi.vo.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class NeedLoginInterceptor implements HandlerInterceptor {
@Resource
JwtUtil jwtUtil;
@Resource
ISysUserService sysUserService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)){
return true;
}
String token = request.getHeader("Authorization");
log.info("=================request start===========================");
log.info("request uri : {}",request.getRequestURI());
log.info("request method: {}",request.getMethod());
log.info("token : {}", token);
log.info("=================request end===========================");
if (StringUtils.isBlank(token)){
Result fail = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(JSON.toJSONString(fail));
return false;
}
Claims claims = jwtUtil.getClaims(token);
SysUser user = sysUserService.checkToken(token);
if (user==null){
Result fail = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(JSON.toJSONString(fail));
return false;
}
UserThreadLocal.put(user);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
UserThreadLocal.remove();
}
}
SysUser user = UserThreadLocal.get();