【问题标题】:How to check if an HttpSession is invalid without having the request如何在没有请求的情况下检查 HttpSession 是否无效
【发布时间】:2018-08-30 11:13:58
【问题描述】:

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

如何从该地图中移除已经失效的会话?

听众

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

【问题讨论】:

    标签: java session httpsession


    【解决方案1】:

    我尝试了这种方法,它似乎工作正常!

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-04
      • 2019-10-22
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 2021-05-04
      • 2019-04-06
      • 2019-10-31
      相关资源
      最近更新 更多