java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class ListenerServletDemo extends HttpServlet implements ServletContextListener,
ServletContextAttributeListener, HttpSessionListener, HttpSessionAttributeListener {
private static int count=0;
//ServletContext创建时该方法被激活
public void contextInitialized(ServletContextEvent sce) {
System.out.println("application对象创建.");
}
//ServletContext被关闭时该方法被激活
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("application对象删除.");
}
//ServletContext的属性增加时该方法被激活
public void attributeAdded(ServletContextAttributeEvent scab) {
System.out.println("application对象新增的属性名 = " + scab.getName() + ",新增的属性值 = "
+ scab.getValue());
}
//ServletContext的属性删除时该方法被激活
public void attributeRemoved(ServletContextAttributeEvent scab) {
System.out.println("application对象删除的属性名 = " + scab.getName() + ",删除的属性值 = "
+ scab.getValue());
}
//ServletContext的属性更新时该方法被激活
public void attributeReplaced(ServletContextAttributeEvent scab) {
System.out.println("application对象更新的属性名 = " + scab.getName() + ",更新的属性值 = "
+ scab.getValue());
}
//HttpSession创建时该方法被激活
public void sessionCreated(HttpSessionEvent se) {
count++;
HttpSession session = se.getSession();
System.out.println("新增加客户端,唯一标识是" + session.getId());
}
//HttpSession删除时该方法被激活
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("关闭窗口");
HttpSession session = se.getSession();
System.out.println("客户端" + session.getId() + "被删除");
count--;
}
//HttpSession的属性增加时该方法被激活
public void attributeAdded(HttpSessionBindingEvent se) {
System.out.println("session对象新增的属性名 = " + se.getName() + ",新增的属性值 = "
+ se.getValue());
}
//HttpSession的属性删除时该方法被激活
public void attributeRemoved(HttpSessionBindingEvent se) {
System.out.println("session对象删除的属性名 = " + se.getName() + ",删除的属性值 = "
+ se.getValue());
}
//HttpSession的属性更新时该方法被激活
public void attributeReplaced(HttpSessionBindingEvent se) {
System.out.println("session对象更新的属性名 = " + se.getName() + ",更新的属性值 = "
+ se.getValue());
}
public static int getCount()
{
return(count);
}
}
web.xml
<listener>
<listener-class>ListenerServletDemo</listener-class>
</listener>