Search code examples
javawebhttpsession

Check my code, I‘m using ThreadLocal to manage HttpSession


I'm use ThreadLocal to manage HttpSession. code as below:

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);
    }
}

Can we do this? If not, how can we improve it? Thanks!


Solution

  • It makes no sense. HttpServletRequest.getSession() returns the same HttpSession object for all requests within the same session. You don't need to cache it. Besides, HttpSession is not thread bound, requests within the same session may come in different threads.