inteceptor在springcontext之前加载,注入必然是null
解决方案
加入注解@Bean
@Configuration
public class WebMVCInterceptor implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(globalInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/userInfo/jwtUser") //登录页
.excludePathPatterns("/register") //用户注册
.excludePathPatterns("/login"); //用户登录
}
/**
* @return globalInterceptor
*/
@Bean
public GlobalInterceptor globalInterceptor() {
return new GlobalInterceptor();
}
}
@Component
public class GlobalInterceptor extends HandlerInterceptorAdapter {
private static Logger logger = LoggerFactory.getLogger(GlobalInterceptor.class);
@Resource
private UserRoleService userRoleService;
/**
* 调用action之前进行拦截
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return super.preHandle(request, response, handler);
}
/**
* 从 cookie 中获取 token
*/
private String getTokenFromCookie(HttpServletRequest request) {
Cookie[] cookies = Optional.ofNullable(request.getCookies()).orElse(new Cookie[0]); // Optional 强制赋默认值,cookies一定不为 null
String cookie = Arrays.stream(cookies).filter(item ->
"X-Auth-Token".equals(item.getName())
).findFirst().map(Cookie::getValue).orElse(null);
return cookie;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
}