ThreadLocal 管理 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要拦截的请求

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值