首页 > 代码库 > 定时销毁session

定时销毁session

通过使用监听定时器,来定时销毁session

demo:

public class MyServletContextListener implements ServletContextListener {

   

public void contextInitialized(ServletContextEvent sce) {

//通过事件源对象得到事件源(ServletContext

ServletContext application = sce.getServletContext();

//创建一个集合用于存储所有session对象

final List<HttpSession> list =Collections.synchronizedList(new ArrayList<HttpSession>());

   

//把集合放到application域中

application.setAttribute("sessions", list);

   

//创建一个计时器对象

Timer t = new Timer();

   

t.schedule(new TimerTask() {

   

@Override

public void run() {

System.out.println("开始扫描了。。。");

for (Iterator iterator = list.iterator(); iterator.hasNext();) {

HttpSession session = (HttpSession) iterator.next();

long l = System.currentTimeMillis()-session.getLastAccessedTime();

if(l>5000){//如果时间大于5秒,把session销毁

System.out.println("session移除了"+session.getId());

session.invalidate();//session销毁

//list.remove(session);//从集合中移除

iterator.remove();

}

   

}

/*for (HttpSession session : list) {

long l = System.currentTimeMillis()-session.getLastAccessedTime();

if(l>5000){//如果时间大于5秒,把session销毁

session.invalidate();//session销毁

list.remove(session);//从集合中移除

}

}*/

}

}, 2000, 5000);//延迟2秒后执行,每间隔5秒执行一次

}

   

public void contextDestroyed(ServletContextEvent sce) {

   

}

   

}

public class MySessionListener implements HttpSessionListener {

   

public void sessionCreated(HttpSessionEvent se) {

HttpSession session = se.getSession();

//得到application对象中的list集合

ServletContext application = session.getServletContext();

//得到session对象,并放入到list集合中

List<HttpSession> list = (List<HttpSession>) application.getAttribute("sessions");

   

list.add(session);

System.out.println("添加了"+session.getId());

}

   

public void sessionDestroyed(HttpSessionEvent se) {

// TODO Auto-generated method stub

   

}

   

}

   

定时销毁session