最近在用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要拦截的请求
本文介绍了一种在Spring Security框架下实现用户登录时将HttpSession绑定到当前线程的方法,以便于在需要的地方获取HttpSession及其中的数据。
7501

被折叠的 条评论
为什么被折叠?



