在整个Tomcat服务器中,Listener使用得非常广泛,它是基于观察者模式设计的,Listener的设计为开发Servlet应用程序提供了一种快捷的手段,能够方便地从另一个纵向维度控制程序和数据。目前在Servlet中提供了6种两类事件的观察者接口,它们分别是:EventListener类型的ServletContextAttributeListener、ServletRequestAttributeListener、ServletRequestListener、HttpSessionAttributeListener和LifecycleListener类型的ServletContextListener、HttpSessionListener。
他们基本涵盖了整个Servlet生命周期中你最感兴趣的每种事件。这些Listener的实现类可以配置在web.xml文件的<listener/>标签中。当然也可以在应用程序中动态添加Listener,需要注意的是ServletContextListener在容器启动之后就不能再添加新的,因为它所监听的事件已经不会再出现了。
如Spring的org.springframework.web.context.ContextLoaderListener就实现了一个ServletContextListener,当容器加载时启动Spring容器。ContextLoaderListener在contextInitialized方法中初始化Spring容器,有几种办法可以加载Spring容器,通过在web.xml的<context-param>标签中配置Spring的applicationContext.xml的路径,文件名可以任意取,如果没有配置,将在/WEB-INF/路径下查找默认的applicationContext.xml文件。ContextLoaderListener的contextInitialized方法代码如下。
public void contextInitialized(ServletContextEvent event){
this.contextLoader = createContextLoader();
if(this.contextLoader == null){
this.contextLoader = this;
}
this.contextLoader.initWebApplicationContext(event.getServletContext());
}