Write a onlineuserlistener.
Package Anni; Import java.util.List;
Import Javax.servlet.ServletContext;
Import javax.servlet.http.HttpSession;
Import Javax.servlet.http.HttpSessionListener;
Import javax.servlet.http.HttpSessionEvent;
public class Onlineuserlistener implements Httpsessionlistener {
public void sessioncreated (Httpsessionevent event) {
}
public void sessiondestroyed (Httpsessionevent event) {
HttpSession session = Event.getsession ();
ServletContext application = Session.getservletcontext ();
User name to get logged in
String username = (string) session.getattribute ("username");
Remove a user name from the online list
List onlineuserlist = (list) application.getattribute ("Onlineuserlist");
Onlineuserlist.remove (username);
SYSTEM.OUT.PRINTLN (username + "Timeout" exit.) ");
}
}
Onlineuserlistener implements the two methods defined by Httpsessionlistener: sessioncreated () and sessiondestroyed (). These two methods can listen to the creation and destruction of the session in the current application. We only use sessiondestroyed () to operate when the session is destroyed.
Get the session that is about to be destroyed from Httpsessionevent, get the username from the session, and remove it from the online list. The last sentence prints a message to the console indicating that the operation was successful, just for debugging purposes, and to delete it during normal operation.
To make the listener work, we add it to Web. xml:
<listener>
<listener-class>anni. Onlineuserlistener</listener-class>
</listener>
Sessiondestoryed (Session destruction) events occur in the following two scenarios:
When the Session.invalidate () method is executed.
Since Session.invalidate () is executed in Logoutservlet.java, Sessiondestory () is triggered to clear the current user from the online user list. We don't have to manipulate the online list in Logoutservlet.java, so Logoutservlet.java's content is now.
public void doget (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException {// Destroy session Request.getsession (). invalidate (); Successful Response.sendredirect ("index.jsp"); }
If the user does not have access to the server for a long time, the server will automatically destroy the timeout session if the maximum timeout period is exceeded.
The 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 corresponding example is in 08-01, in order to verify that Onlineuserlistener is performing properly, we can log in to two users, one click to log off, the other waits a minute, and then the output information can be seen in the console.
Listener Listener's Httpsessionlistener