1. Create Myservletcontextlistener to implement Httpservletcontextlistener interface
@Override Public voidcontextdestroyed (Servletcontextevent sce) {} @Override Public voidcontextinitialized (Servletcontextevent sce) {//Create a list collection to hold all httpsession, must be locking for this collection (multi-threaded access) FinalListNewArraylist()); //ServletContext Add this collectionSce.getservletcontext (). SetAttribute ("list", list); Timer Timer=NewTimer ();//class of time schedulingTimer.schedule (NewTimerTask () {//Scheduled Tasks@Override Public voidrun () {System.out.println ("Started scanning ... "); for(Iterator Iterator =list.iterator (); Iterator.hasnext ();) {HttpSession HttpSession=(HttpSession) iterator.next (); //calculates the time that the session already exists (the current system time-httpsession the last access time) LongL=system.currenttimemillis ()-Httpsession.getlastaccessedtime (); //Remove session If survival time is greater than 10 seconds if(l>10000) { //invalidation, removing httpsesion from the collectionSYSTEM.OUT.PRINTLN ("Session Expired:" +Httpsession.getid ()); Httpsession.invalidate (); Iterator.remove (); } } } //delay: Start execution in seconds (sec)//period: Time between execution (seconds)}, 2000, 5000); }
2. Create Myhttpsessionlistener to implement Httpsessionlistener interface
@Override publicvoid sessioncreated (httpsessionevent arg0) { // when the server creates a httpsession, it adds HttpSession to the list collection HttpSession HttpSession = arg0.getsession (); = Httpsession.getservletcontext (); List<HttpSession> list = (list); System.out.println ("Session creation added" +Httpsession.getid ()); List.add (httpSession); }
Note: To implement the listener interface, be sure to configure the Web. xml file
Small example of listeners: Use Httpsessionlistener and Httpservletcontextlistener to implement timed destruction httpsession