ThreadLocal 管理 HttpSession

本文介绍了一种在Spring Security框架下实现用户登录时将HttpSession绑定到当前线程的方法,以便于在需要的地方获取HttpSession及其中的数据。

   最近在用spring security控制系统的权限, 在用户登陆的时候,在方法loadUserByUsername里验证用户名是否正确时,想获取HttpSession,并把登陆用户保存到session中,此时发现在当前方法中无法获取HttpSession;类似的,

在系统中,在无法获取HttpSession的时候,想使用session中保存的数据是很困难的;在我们项目中,我们是这样解决的:

 基本思路:创建一个Filter,在请求前把HttpSession绑定到当前线程中,在使用时,从当前线程获取HttpSession

 

1 保存HttpSession的上下文:

 

public class UserContext {
    private static ThreadLocal<HttpSession> tl = new ThreadLocal<HttpSession>();

    public static void setSession(HttpSession session) {
        tl.set(session);
    }

    public static HttpSession getSession() {
        return tl.get();
    }
}

 

2 绑定和注销绑定的Filter

  

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                HttpServletRequest req =(HttpServletRequest) request;
		HttpServletResponse res =(HttpServletResponse) response;
		//当前线程绑定HttpSession
		UserContext.setSession(req.getSession(true));//开启session
		chain.doFilter(request, response);
		UserContext.setSession(null);//取消对session的引用
	}

 

3 在web.xml中配置Filter要拦截的请求

### ThreadLocal Session 管理与拦截器实现原理 #### 1. 原理解析 ThreadLocal 是 Java 中的一种机制,它允许创建线程局部变量。这意味着每个线程都有独立的副本,从而实现了线程间的隔离[^1]。在 Web 应用中,Session 的管理通常涉及多个请求之间的状态保持。如果使用传统的全局对象来保存 Session 数据,则可能会因为多线程环境而导致数据混乱。 通过结合拦截器(Interceptor),可以在每次 HTTP 请求到达时动态分配并绑定一个唯一的 Session 对象到当前线程上,利用 ThreadLocal 来存储该对象。当请求结束时,再清理掉这个本地线程中的 Session 变量,防止内存泄漏[^3]。 #### 2. 实现步骤说明 以下是基于 Spring MVC 或类似的框架下,如何借助拦截器和 ThreadLocal 进行会话管理的一个典型方案: - **定义 ThreadLocal 存储类** 创建一个专门用来持有 HttpSession 的工具类,内部封装了一个静态类型的 `ThreadLocal<HttpSession>` 成员变量。 ```java public class SessionHolder { private static final ThreadLocal<HttpSession> threadLocalSession = new ThreadLocal<>(); public static void set(HttpSession session) { threadLocalSession.set(session); } public static HttpSession get() { return threadLocalSession.get(); } public static void remove() { threadLocalSession.remove(); } } ``` - **配置自定义拦截器** 编写一个继承于 HandlerInterceptor 接口的具体实现类,在 preHandle 方法里获取当前用户的 Session 并存入上述工具类;postHandle 和 afterCompletion 则分别负责释放资源以及清除 ThreadLocal 上的数据。 ```java import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SessionManagementInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(false); // 不强制创建新session if (session != null){ SessionHolder.set(session); } else{ System.out.println("No active session found."); } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { SessionHolder.remove(); } } ``` - **注册拦截器至Spring上下文中** 最后一步就是把刚才编写的拦截器加入到应用程序的整体过滤链当中去。这可以通过 XML 配置文件或者 Java Config 方式完成。 ```java @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Bean public SessionManagementInterceptor getSessionManagementInterceptor(){ return new SessionManagementInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getSessionManagementInterceptor()).addPathPatterns("/secure/**"); } } ``` 以上代码展示了完整的流程设计思路及其具体实践方法[^2]。 #### 3. 注意事项 尽管这种方法能够很好地解决跨层调用期间访问同一份用户信息的需求,但也存在一些潜在风险需要注意: - 如果忘记在适当时候移除 ThreadLocal 中的内容,就可能导致严重的内存泄露问题; - 当业务逻辑变得复杂起来之后,过度依赖此类模式反而会让程序结构显得臃肿难懂。 ### 结论 综上所述,采用 ThreadLocal 加上拦截器的方式确实是一种优雅高效的解决方案,适用于需要在线程范围内维持特定状态的应用场景之中。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值