我使用 ThreadLocal 来管理 HttpSession。代码如下:
public class HttpSessionLocal {
private static ThreadLocal<HttpSession> threadLocal = new ThreadLocal<HttpSession>();
public static HttpSession getSession(HttpServletRequest request) {
HttpSession session = threadLocal.get();
if (session == null) {
threadLocal.set(request.getSession());
}
return threadLocal.get();
}
public static void setSession(HttpSession session) {
threadLocal.set(session);
}
}
public class SessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
}
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSessionLocal.setSession(null);
}
}
我们可以这样做吗?如果没有,我们如何改进它?谢谢!