ThreadLocal存储当前登录用户信息

ThreadLocal可以将用户信息保存在线程中,当请求结束后我们在把保存的信息清除掉。这样我们才开发的时候就可以直接从全局的ThreadLocal中很方便的获取用户信息

/**
 * 保存用户对象的ThreadLocal
 *
 * @author wangql
 */
@Component
public class UserInfoThreadHandler{

    private static final ThreadLocal<SysUser> userThreadLocal = new ThreadLocal<>();

    /**
     * 添加当前登录用户方法
     */
    public static void addCurrentUser() {

        //登录对象从这里获取然后set进ThreadLocal
        //具体根据业务逻辑来
        SysUser sysUser = new SysUser();


        userThreadLocal.set(sysUser);
    }

    public static SysUser getCurrentUser() {
        return userThreadLocal.get();
    }

    /**
     * 防止内存泄漏
     */
    public static void remove() {
        userThreadLocal.remove();
    }

}

可以利用拦截器操作

/**
 * 将登录用户存入ThreadLocal
 * @author wangql
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoThreadHolder.addCurrentUser();
        return true;
    }

    /**
     * 避免内存泄露
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserInfoThreadHolder.remove();
    }
}

注册拦截器


@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;


    //注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
    }

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addExposedHeader("Authorization");
        return corsConfiguration;
    }

    /**
     * 配置跨域
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }

}

你可能感兴趣的:(java,servlet,开发语言)