拦截器实现Token校验 + ThreadLocal

一、教学目标
创建拦截器,对除登录注册外的接口进行token校验。
使用ThreadLocal存储当前用户ID。
二、核心知识点(简要)
HandlerInterceptor:Spring MVC拦截器接口。
ThreadLocal:线程局部变量,每个线程独立存储。
token校验:从请求头获取token,解析验证,若无效返回401。
三、操作步骤

  1. 创建UserContext
    右键util文件夹,新建java类:UserContext
    UserContext中的代码如下:
package com.weitoutiao.util;

public class UserContext {
    private static final ThreadLocal<Integer> currentUserId = new ThreadLocal<>();

    public static void setCurrentUserId(Integer userId) {
        currentUserId.set(userId);
    }
    public static Integer getCurrentUserId() {
        return currentUserId.get();
    }
    public static void clear() {
        currentUserId.remove();
    }
}
  1. 创建JwtInterceptor
    右键com.weitoutiao,新建java类:interceptor.JwtInterceptor
    interceptor.JwtInterceptor中的代码如下:
package com.weitoutiao.interceptor;

import com.weitoutiao.util.JwtUtil;
import com.weitoutiao.util.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            if (jwtUtil.validateToken(token)) {
                Integer userId = jwtUtil.getUserIdFromToken(token);
                UserContext.setCurrentUserId(userId);
                return true;
            }
        }
        response.setStatus(401);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("{\"code\":401,\"message\":\"未登录或token失效\"}");
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }
}
  1. 配置拦截器
    右键config文件夹,新建java类:InterceptorConfig
    InterceptorConfig中的代码如下:
package com.weitoutiao.config;

import com.weitoutiao.interceptor.JwtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Autowired
    private JwtInterceptor jwtInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login", "/user/register");
    }
}
posted on 2026-06-24 10:45  爱我的果果吖  阅读(8)  评论(0)    收藏  举报