标签:port remove context ssi iter tde set override Stub
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 } }
标签:port remove context ssi iter tde set override Stub
原文地址:https://www.cnblogs.com/happydts/p/9676617.html