The session creation event occurs every time a new session is created, and a similar session failure event occurs every time a session fails.
This interface also contains only two methods, corresponding to the creation and invalidation of the session, respectively:
# public void sessioncreated (httpsessionevent se);
# public void sessiondestroyed (httpsessionevent se);
My web App wants to know exactly how many users are using it?
We can use event listeners (Listener) defined in the servlet specification to solve this problem and achieve more accurate online demographics. For each user being accessed, the Java EE Application Server creates a corresponding HttpSession object for it. Conversely, when the browser accesses the end time-out, the Java application Server destroys the corresponding HttpSession object, triggering the HttpSession destroy event, The Sessiondestroyed method that invokes the registered Httpsessionlistener event listener at the same time.
Import Javax.servlet.http.HttpSessionListener; Import javax.servlet.http.HttpSessionEvent; public class Sessioncounter implements Httpsessionlistener {private static int activesessions = 0; /* Session Creation Event */public void sessioncreated (httpsessionevent se) {ServletContext ctx = Event.getsession (). Getse Rvletcontext (); Integer numsessions = (integer) ctx.getattribute ("Numsessions"); if (numsessions = = null) {numsessions = new Integer (1); } else {int count = Numsessions.intvalue (); Numsessions = new Integer (count + 1); } ctx.setattribute ("Numsessions", numsessions); }/* Session failure event */public void sessiondestroyed (httpsessionevent se) {servletcontext ctx=se.getsession (). Getservle Tcontext (); Integer numsessions = (integer) ctx.getattribute ("Numsessions"); if (numsessions = = null) Numsessions = new Integer (0); } else {intCount = Numsessions.intvalue (); Numsessions = new Integer (count-1); } ctx.setattribute ("Numsessions", numsessions); } }
in this solution, whenever a session is created or destroyed, Sessioncounter is notified of this class, and of course the reason for this is that the configuration must be done in the Web. xml file. such as the following configuration code:
<listener> <listener-class>demo.listener.SessionCounter</listener-class> </ Listener>
sessiondestoryed (Session destruction) events occur in the following two scenarios:
1. When executing the Session.invalidate () method
2. If the user does not have access to the server for a long time , the server will automatically destroy the time-out session if the maximum timeout is exceeded.
Session timeout can be set in Web. XML, in order to easily see the timeout effect, we set the timeout to the minimum value
<session-config> <session-timeout>1</session-timeout> </session-config>
The time unit is one minute and can only be an integer, and if it is 0 or negative, the session will never time out
The use of Httpsessionlistener