基本概念
当Web应用在Web容器中运行时,Web应用内部会不断的发生各种事件:如Web应用被启动,Web应用被停止,用户session开始,用户session结束等。通常来说,这些事件对开发者是透明的。实际上,Servlet中提供了大量的监听器来监听Web应用的状态,监听器就是Listener。使用Listener只需要两步:
定义Listener的实现类
通过注解或者在web.xml文件中配置这个Listener
主要的监听器类
ServletContextListener:用于监听Web容器的启动和关闭
ServletContextAttributeListener:用于监听application范围内的属性变化
ServletRequestListener:用于监听用户的请求
ServletRequestAttributeListener:用于监听request范围内的属性变化
HttpSessionListener:用于监听用户session的创建和销毁
HttpSessionAttributeListener:用于监听session范围内的属性变化
举个栗子
//监听web容器的启动与关闭
@WebListener
public class ContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("Web容器开启");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("Web容器<a href="/tag/guanbi/" target="_blank" class="keywords">关闭</a>");
}
}
//监听application范围内属性的变化
@WebListener
public class ContextAttributeListener implements ServletContextAttributeListener {
@Override
public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
String key = servletContextAttributeEvent.getName();
Object value = servletContextAttributeEvent.getValue();
System.out.println("application中替换了"+key+",值为:"+value);
}
@Override
public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
String key = servletContextAttributeEvent.getName();
Object value = servletContextAttributeEvent.getValue();
System.out.println("application中<a href="/tag/shanchu/" target="_blank" class="keywords">删除</a>了"+key+",值为:"+value);
}
@Override
public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
String key = servletContextAttributeEvent.getName();
Object value = servletContextAttributeEvent.getValue();
System.out.println("application中<a href="/tag/zengjia/" target="_blank" class="keywords">增加</a>了"+key+",值为:"+value);
}
}
其他的使用方法都是类似的。下一节,咱们看一下JSP2的特性