WEB容器监听器详解 ServletContextListener

来源:互联网 发布:量化对冲软件 编辑:程序博客网 时间:2024/05/16 01:44


WEB容器监听器ServletContextListener主要用来监听容器启动和 销毁的时候需要做一些操作,就可以使用这个监听器来做。

ServletContextListener在spring启动前启动。


我们实现一个简单的监听器,需要继承接口ServletContextListener:

[java] view plain copy print?在CODE上查看代码片派生到我的代码片
  1.  * 一个测试的监听器例子  
  2.  * @author zhuli  
  3.  * @date 2014-7-26  
  4.  */  
  5. public class TestContextLister implements ServletContextListener {  
  6.   
  7.     @Override  
  8.     public void contextInitialized(ServletContextEvent sce) {  
  9.         System.out.println("==============================容器装载");  
  10.   
  11.     }  
  12.   
  13.     @Override  
  14.     public void contextDestroyed(ServletContextEvent sce) {  
  15.         System.out.println("==============================容器销毁");  
  16.     }  
  17.   
  18. }  

ServletContextListener 实现两个接口,一个是容器启动的时候,一个是容器销毁的时候:

[java] view plain copy print?在CODE上查看代码片派生到我的代码片
  1. public interface ServletContextListener extends EventListener {  
  2.     /** 
  3.      ** Notification that the web application initialization 
  4.      ** process is starting. 
  5.      ** All ServletContextListeners are notified of context 
  6.      ** initialization before any filter or servlet in the web 
  7.      ** application is initialized. 
  8.      */  
  9.   
  10.     public void contextInitialized ( ServletContextEvent sce );  
  11.   
  12.     /** 
  13.      ** Notification that the servlet context is about to be shut down. 
  14.      ** All servlets and filters have been destroy()ed before any 
  15.      ** ServletContextListeners are notified of context 
  16.      ** destruction. 
  17.      */  
  18.     public void contextDestroyed ( ServletContextEvent sce );  
  19. }  

在web.xml中的配置:

[html] view plain copy print?在CODE上查看代码片派生到我的代码片
  1. <listener>  
  2.     <listener-class>com.xxx.controller.web.TestContextLister</listener-class>  
  3. </listener>  

容器启动后,会在容器启动的日志中看到:

[java] view plain copy print?在CODE上查看代码片派生到我的代码片
  1. ==============================容器装载  
  2. 2014-07-26 08:54:01.302:INFO:/:Initializing Spring FrameworkServlet 'apiServlet'
0 0