1.编写一个ThreadLocal类,用于存放token

    private static final ThreadLocal<String> TOKEN = new ThreadLocal();

    public TokenThreadLocal() {
    }

    public static void setToken(String token) {
        TOKEN.set(token);
    }

    public static String getToken() {
        return TOKEN.get();
    }

    public static void remove() {
        TOKEN.remove();
    }

2.编写token拦截器,实现HandlerInterceptor类,重写preHandle和afterCompletion方法用于存放和移除ThreadLocal中的token。

@Component
public class TokenInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            TokenThreadLocal.setToken(token);
        }
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TokenThreadLocal.remove();
    }
}

3.注册第二步的拦截器

@Configuration
@ConditionalOnClass({WebMvcConfigurer.class})
public class TokenConfig implements WebMvcConfigurer {

    @Autowired
    TokenInterceptor tokenInterceptor;

    public TokenConfig() {

    }

    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.tokenInterceptor);
        //.order(Ordered.LOWEST_PRECEDENCE)可以指定顺序为最后,先让其他拦截器生效
    }
}