import java.io.FileOutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public final class SessionListener implements HttpSessionActivationListener,
HttpSessionListener, ServletContextListener {
private static final long serialVersionUID = 1L;
ServletContext context;
int users = 0;
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
public void sessionCreated(HttpSessionEvent event) {
users++;
log("sessionCreated(" + event.getSession().getId() + "),目前有" + users
+ "个用户");
context.setAttribute("users", new Integer(users));
System.out.println("sessionCreated(" + event.getSession().getId()
+ "),目前有" + users + "个用户");
}
public void sessionDestroyed(HttpSessionEvent event) {
users--;
log("sessionDestroyed(" + event.getSession().getId() + "),目前有" + users
+ "个用户");
}
public void contextDestroyed(ServletContextEvent sce) {
log("contextDestroyed()-->ServletContext被销毁");
}
public void contextInitialized(ServletContextEvent sce) {
this.context = sce.getServletContext();
log("contextInitialized()-->ServletContext初始化了");
}
public void sessionDidActivate(HttpSessionEvent se) {
log("sessionDidActivate(" + se.getSession().getId() + ")");
}
public void sessionWillPassivate(HttpSessionEvent se) {
log("sessionWillPassivate(" + se.getSession().getId() + ")");
}
private void log(String message) {
PrintWriter out = null;
try {
out = new PrintWriter(new FileOutputStream("c:\\logger.txt"), true);
out.println(new java.util.Date().toLocaleString()
+ "::Form ExampleListener:" + message);
out.close();
} catch (Exception e) {
out.close();
e.printStackTrace();
}
}
}