无法从Filter中获取在Session Listener中设置的ThreadLocal变量

时间:2015-06-17 10:39:02

标签: java

我希望在会话被销毁时为threadLocal设置一个值,并希望在Filter中获取它。但我无法得到它,它显示为null。我怎么能得到它?

下面是Listener的代码:

public class MySessionListener implements HttpSessionListener {
    public static ThreadLocal<String> threadLocal = new ThreadLocal<String>();
    /**
     * Default constructor. 
     */
    public MySessionListener() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
     */
    public void sessionCreated(HttpSessionEvent event)  {

    }

    /**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */
    public void sessionDestroyed(HttpSessionEvent event)  {

        threadLocal.set("timeout");
        System.out.println(threadLocal.get());  //timeout
    }
}

Filter中的代码部分:

String flag = MySessionListener.threadLocal.get();

System.out.println(flag); //null

if (flag != null && flag.equals("timeout")) {
    MySessionListener.threadLocal.set("");
    dispatcher = this.request.getRequestDispatcher("/relogin");
    dispatcher.forward(request, response);
} else {
    dispatcher = this.request.getRequestDispatcher("/error");
    dispatcher.forward(request, response);
}

0 个答案:

没有答案