如何在没有请求的情况下检查HttpSession是否无效

时间:2018-03-21 10:59:57

标签: java session httpsession

我有一个HttpSession和ip的Map,在初始化请求时添加。它通常在会话被销毁时删除,但有时不会发生,我想手工完成。

如何从此地图中删除已经失效的会话?

监听

...
private static final Map<HttpSession, String> sessions = new ConcurrentHashMap<>();

    @Override
    public void requestInitialized(ServletRequestEvent ev) {
        HttpServletRequest request = (HttpServletRequest) ev.getServletRequest();
        HttpSession session = request.getSession();
        if(session.isNew()){
            sessions.put(session, request.getRemoteAddr());
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent ev) {
        sessions.remove(ev.getSession());
    }
...

1 个答案:

答案 0 :(得分:0)

我试试这种方式似乎工作正常!

public static void cleanUpMemorySessions() {
    sessions.entrySet().forEach((entry) -> {
        try {
            entry.getKey().isNew();
        } catch(IllegalStateException e) {
            sessions.remove(entry.getKey());
        }
    });
}