listener之定时销毁 session

Posted happydts

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了listener之定时销毁 session相关的知识,希望对你有一定的参考价值。

package com.deng.listenner;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;

public class MyContextListener implements ServletContextListener{

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        ServletContext application = arg0.getServletContext();
        final List<HttpSession> al = Collections.synchronizedList(new ArrayList<HttpSession>());
        application.setAttribute("sessions", al);
        
        Timer t = new Timer();
        t.schedule(new TimerTask() {
            
            @Override
            public void run() {
                System.out.println("开始扫描了。。。");
                // TODO Auto-generated method stub
                for (Iterator iterator = al.iterator(); iterator.hasNext();) {
                    HttpSession httpSession = (HttpSession) iterator.next();
                    
                    long l=System.currentTimeMillis()-httpSession.getLastAccessedTime();
                    if(l>5000){
                        System.out.println("session销毁了。。。"+httpSession.getId());
                        httpSession.invalidate();
                        
                        iterator.remove();
                    }
                }
            }
        }, 1000, 1000);
    }

}

用 arraylist<HttpSession>放session集合,用计时器来检测session是否超时


package com.deng.listenner;

import java.util.ArrayList;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MySessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent arg0) {
        // TODO Auto-generated method stub
        HttpSession session=arg0.getSession();
        ServletContext application = session.getServletContext();
        ArrayList<HttpSession> sessions = (ArrayList<HttpSession>) application.getAttribute("sessions");
        sessions.add(session);
        
        System.out.println("session添加了。。");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent arg0) {
        // TODO Auto-generated method stub

    }

}

 






以上是关于listener之定时销毁 session的主要内容,如果未能解决你的问题,请参考以下文章

定时销毁session

java web 之 listen 与 filter

servlet session listener

厚积薄发系列之listener

Servlet-Listener

Listener