zoukankan      html  css  js  c++  java
  • Java通过遍历sessionId获取服务器所有会话session

      Servlet2.1之后不支持SessionContext里面getSession(String id)方法,也不存在遍历所有会话Session的方法。但是,我们可以通过HttpSessionListener监听器和全局静态map自己实现一个SessionContext,然后用SessionContext管理一份服务器所有会话的Session。

    1.web.xml添加一个监听器

    <listener>
        <listener-class>listener.MySessionListener</listener-class>
    </listener>

    2.定义一个SessionContext:MySessionContext

    public class MySessionContext {
    private static HashMap mymap = new HashMap();
    public static synchronized void AddSession(HttpSession session) { if (session != null) { mymap.put(session.getId(), session); } }
    public static synchronized void DelSession(HttpSession session) { if (session != null) { mymap.remove(session.getId()); } }
    public static synchronized HttpSession getSession(String session_id) { if (session_id == null) return null; return (HttpSession) mymap.get(session_id); } }

    3.任何Session的创建和删除都用自己的SessionContext管理起来:MySessionListener

    public class MySessionListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {   MySessionContext.AddSession(httpSessionEvent.getSession()); }
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { HttpSession session = httpSessionEvent.getSession(); MySessionContext.DelSession(session); } }

      然后就实现了任何时候都可以通过遍历SessionContext而得到所有会话的Session。

      有什么用呢?你可以定期清理过时的Session呢!(注意,Session超时了以及你换地方登陆了并不会删除用户的Session,其只是Session对应的时间戳让你无法再使用对应的Session,或者是浏览器的Cookie丢失了原先浏览器里面存在的SessionId而已,因此定时清理Session也会让服务器内存压力小很多)。

  • 相关阅读:
    【源码学习之spark core 1.6.1 standalone模式下的作业提交】
    【源码学习之spark streaming 1.6.1 】
    spark udf 初识初用
    spark 累加历史 + 统计全部 + 行转列
    spark 都用了哪些开源东东
    kafka 官方示例代码--消费者
    104. 二叉树的最大深度
    237. 删除链表中的节点
    Leetcode-167. Two Sum II
    Leetcode-215. Kth Largest Element in an Array
  • 原文地址:https://www.cnblogs.com/jing99/p/7826478.html
Copyright © 2011-2022 走看看