原因:拦截器在bean初始化前执行的,这时候redisUtil是null,需要通过下面这个方式去获取
主要解决的代码: WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); redisOpsUtil = wac.getBean(RedisOpsUtil.class);
package com.hzh.studyonline.config;
import com.hzh.studyonline.util.JwtUtil;
import com.hzh.studyonline.util.RedisOpsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
RedisOpsUtil redisOpsUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
String phone = request.getHeader("phone");
if(!(handler instanceof HandlerMethod)){
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
JwtIgnore annotation = handlerMethod.getBeanType().getAnnotation(JwtIgnore.class);
if(annotation == null){
if(method.isAnnotationPresent(JwtIgnore.class)){
annotation = method.getAnnotation(JwtIgnore.class);
log.info("请求方法 {} 上有注解 {} ",method.getName(),annotation);
}
}
if (annotation!=null){
return true;
}
JwtUtil jwtUtil = new JwtUtil();
boolean parse = jwtUtil.parse(token);
if (redisOpsUtil==null){
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
redisOpsUtil = wac.getBean(RedisOpsUtil.class);
}
String redisToken =(String) redisOpsUtil.hget("token", phone);
if (redisToken==null){
log.info("redisToken过期 电话是:{} 的用户 ",phone);
return false;
}
if (parse==true && redisToken.equals(token)){
return true;
}
return false;
}
}
|