2

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!

ddmps
  • 4,350
  • 1
  • 19
  • 34
albert
  • 27
  • 7

2 Answers2

0

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.

Shafin Mahmud
  • 3,831
  • 1
  • 23
  • 35
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • actually I have got a problem, that one user found his username is another people when he was login in website. But I have save the user information in httpsession. I think the session is mixed up, but the frequency is very low. So I decided to use Threadlocal to management httpsession. – albert May 26 '13 at 10:24
0

You're code will not work as intended as the http request thread is different than the thread spawn by the container to deal with the sessionDestroyed event.

I can't imagine why you keep the http session in a thread local and require the HttpServletRequest as argument to the HttpSessionLocal.getSession. If you have a reference to the request you can get the http session with: request.getSession().

dcernahoschi
  • 14,968
  • 5
  • 37
  • 59
  • actually I have got a problem, that one user found his username is another people when he was login in website. But I have save the user information in httpsession. I think the session is mixed up. So I decided to use Threadlocal to management httpsession. – albert May 26 '13 at 10:19