springboot filter 和 interceptor 使用

userholder

public class UserHolder {
    private static ThreadLocal<String> userThreadLocal = new ThreadLocal<>();

    //为当前的线程变量赋值上用户信息
    public static void setLoginUser(String user) {
        userThreadLocal.set(user);
    }
    //从当前线程变量中获取用户信息
    public static String getLoginUser() {
        return userThreadLocal.get();
    }


    public static void removeUser() {
        userThreadLocal.remove();
    }

}

filter

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String header = request.getHeader("token");
        String requestURI = request.getRequestURI();
        if(header != null){
//            UserHolder.setLoginUser("xiaosu");
        }
//        UserHolder.set("xiaoai");
        try{
            filterChain.doFilter(request,response);
        }finally {
            UserHolder.remove();
        }
    }

}

 

 

interceptor

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterpector implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader("token");
        if(header != null){
//            UserHolder.setLoginUser("xiaosu");
        }
        UserHolder.setLoginUser("inter ---xiaoai");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}

 config

import com.stepwise.script.interceptor.UserInterpector;
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 WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new UserInterpector());
    }
}

 

posted @ 2023-04-12 17:23  冬马党  阅读(26)  评论(0编辑  收藏  举报