監聽器的小樣本:利用HttpSessionListener和HttpServletContextListener實現定時銷毀HttpSession

來源:互聯網
上載者:User

標籤:delay   getattr   val   creat   nbsp   context   pre   間隔   樣本   

1.建立MyServletContextListener實現HttpServletContextListener介面

    @Override    public void contextDestroyed(ServletContextEvent sce) {            }    @Override    public void contextInitialized(ServletContextEvent sce) {            //建立一個list集合來存放所有的httpSession,必須要為這個集合加鎖(多線程訪問)        final List<HttpSession>  list=Collections.synchronizedList(new ArrayList<HttpSession>());        //servletContext添加這個集合        sce.getServletContext().setAttribute("list", list);                        Timer timer=new Timer();//時間調度的類        timer.schedule(new TimerTask() {            //調度的任務            @Override            public void run() {                System.out.println("開始掃描了。。。");                for (Iterator iterator = list.iterator(); iterator.hasNext();) {                    HttpSession httpSession = (HttpSession) iterator.next();                    //計算session已存在的時間(當前的系統時間-httpSession最後一次訪問的時間)                    long l=System.currentTimeMillis()-httpSession.getLastAccessedTime();                    //存活時間大於10秒 則移除session                    if (l>10000) {                        //失效,從集合中刪除httpSesion                        System.out.println("session失效了:"+httpSession.getId());                        httpSession.invalidate();                        iterator.remove();                    }                                }                        }            //delay: 幾秒後開始執行(秒)            //period:  執行的間隔時間(秒)        }, 2000, 5000);        }

 

2.建立MyHttpSessionListener實現HttpSessionListener介面

    @Override    public void sessionCreated(HttpSessionEvent arg0) {        //伺服器一建立httpSession,就向list集合中添加HttpSession        HttpSession httpSession = arg0.getSession();        ServletContext application = httpSession.getServletContext();        List<HttpSession> list = (List<HttpSession>) application.getAttribute("list");        System.out.println("session建立添加了"+httpSession.getId());        list.add(httpSession);    }

注意:實現listener介面 ,一定要配置web.xml檔案

 

監聽器的小樣本:利用HttpSessionListener和HttpServletContextListener實現定時銷毀HttpSession

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.