Test environment: Tomcat 5.0.28
Tomcat with more than 5.5 is required, and a bug occurs at 5.5, and sessiondestroyed runs twice.
Sessions in Java Web
Sessionlistener
- you can use sessionlistenr to listen to the creation and destruction of sessions. Steps:
1. write a class mysessionlistener to implement javax. servlet. HTTP. httpsessionlistener interface and its sessioncreated () and sessiondestroyed () methods
2. in the web. configure sessionlistener in XML: listener >
listener-class > full name of mysessionlistener class listener-class >
listener >
- When the session is created and destroyed, the container will call the sessioncreated () method and sessiondestroyed () method of sessionlistener respectively. In the two methods, a parameter object httpsessionevent is input, you can use the getsession () method of this object to obtain the session object.
Application: Online count statistics
Import Java. util. hashset;
Import Javax. servlet. servletcontext;
Import Javax. servlet. http. httpsession;
Import Javax. servlet. http. httpsessionevent;
Import Javax. servlet. http. httpsessionlistener;
Public Class Mysessionlistener Implements Httpsessionlistener {
Public Void Sessioncreated (httpsessionevent event ){
Httpsession = Event. getsession ();
Servletcontext Application = Session. getservletcontext ();
// All sessions are saved by a hashset in the application range.
Hashset sessions = (Hashset) application. getattribute ( " Sessions " );
If (Sessions = Null ){
Sessions = New Hashset ();
Application. setattribute ( " Sessions " , Sessions );
}
// All newly created sessions are added to the hashset set.
Sessions. Add (session );
// The sessions set can be retrieved from the application range elsewhere. // Use sessions. Size () to obtain the number of sessions in the current activity, that is, "Number of online users"
}
Public Void Sessiondestroyed (httpsessionevent event ){
Httpsession = Event. getsession ();
Servletcontext Application = Session. getservletcontext ();
Hashset sessions = (Hashset) application. getattribute ( " Sessions " );
// All destroyed sessions are removed from the hashset set.
Sessions. Remove (session );
}
}