写了一个MyServletContextListener类来测试MyServletContextListener接口。
package com.test.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("context Destroyed invoked "+sce.getServletContext());
}
public void contextInitialized(ServletContextEvent sce) {
System.out.println("context Initialized invoked "+sce.getServletContext());
}
}
在启动服务器时,启用信息中会打印出如下信息,说明我们的MyServletContextListener 监听器已监听到服务器的启动
信息: Setting DefaultObjectTypeDeterminer as default ... context Initialized invoked org.apache.catalina.core.ApplicationContextFacade@10bbf9e
在服务器重新加载时,监听器获取到context销毁并立刻初始化的事件。
信息: Reloading this Context has started context Destroyed invoked org.apache.catalina.core.ApplicationContextFacade@194d372 context Initialized invoked org.apache.catalina.core.ApplicationContextFacade@17b0998
接下来再看ServletContextAttributeListener监听器,它用来监听application属性的创建,修改,删除动作。
package com.test.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
public class MyServletContextAttributeListener implements
ServletContextAttributeListener {
public void attributeAdded(ServletContextAttributeEvent scab) {
System.out.println("attribute added");
System.out.println(scab.getName()+":"+scab.getValue());
}
public void attributeRemoved(ServletContextAttributeEvent scab) {
System.out.println("attribute removed");
System.out.println(scab.getName()+":"+scab.getValue());
}
public void attributeReplaced(ServletContextAttributeEvent scab) {
System.out.println("attribute replaced");
System.out.println(scab.getName()+":"+scab.getValue());
}
}
listener.jsp,在此页面中创建一个aa属性,并替换三次
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<body>
<%
application.setAttribute("aa","bb");
application.setAttribute("aa","cc");
application.setAttribute("aa","dd");
application.setAttribute("aa","ee");
%>
</body>
</html>
在管理控制台打印出
attribute added aa:bb attribute replaced aa:bb attribute replaced aa:cc attribute replaced aa:dd
上面第1,2行表示新建一个属性名是aa且值是bb的属性。
3,4行表示aa属性的值被替换了,旧值是bb(注意,这里只能取出旧值)。余下类似。
listener2.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<body>
<%
application.removeAttribute("aa");
%>
</body>
</html>
打开 listener2.jsp页面会在管理控制台打印出如下信息,表示属性被删除了。
attribute removed aa:ee
session的监听器与application的类似,不再一一介绍。