洪福必成给你最好的提示

ServletContextListener 详解

1.首先来看一看源码 该类的源码

 

[java] view plain copy
 
  1. public interface ServletContextListener extends EventListener {  
  2.   
  3.     /** 
  4.      * Receives notification that the web application initialization 
  5.      * process is starting. 
  6.      * 
  7.      * <p>All ServletContextListeners are notified of context 
  8.      * initialization before any filters or servlets in the web 
  9.      * application are initialized. 
  10.      * 
  11.      * @param sce the ServletContextEvent containing the ServletContext 
  12.      * that is being initialized 
  13.      */  
  14.     public void contextInitialized(ServletContextEvent sce);  
  15.   
  16.     /** 
  17.      * Receives notification that the ServletContext is about to be 
  18.      * shut down. 
  19.      * 
  20.      * <p>All servlets and filters will have been destroyed before any 
  21.      * ServletContextListeners are notified of context 
  22.      * destruction. 
  23.      * 
  24.      * @param sce the ServletContextEvent containing the ServletContext 
  25.      * that is being destroyed 
  26.      */  
  27.     public void contextDestroyed(ServletContextEvent sce);  
  28. }  

 

此接口中提供了两个方法,用于监听ServletContext  的创建和销毁,也就是监听ServletContext 的生命周期,可以说成是监听Web 应用的生命周期,当web应用启动后,就会触发ServletContextEvent 事件 当此事件执行时,就会被ServletContextListener 监听器监听到,会调用他的 contextInitialized(ServletContextEvent sce)  方法,通过sce 可以获取ServletContext 实例,初始化一些数据,例如缓存的应用,如,创建数据库连接,读取数据库数据,通过setAttribute(“”,obj) 方法设置数据,然后就是可通过servlet 获取servletContext 的实例,通过getAttribute("") 获取设置的数据

实现代码:

 

[java] view plain copy
 
  1. public class MyContextListener implements ServletContextListener {  
  2.     private ServletContext context = null;  
  3.   
  4.     public void contextInitialized(ServletContextEvent event) {  
  5.         context = event.getServletContext();  
  6.         User user = DatabaseManager.getUserById(1);  
  7.         context.setAttribute("user1", user);  
  8.     }  
  9.    
  10.     public void contextDestroyed(ServletContextEvent event) {  
  11.         User user = (User)context.getAttribute("user1");  
  12.         DatabaseManager.updateUserData(user);  
  13.         this.context = null;  
  14.     }  
  15. }  


如果是web 项目 最后一步是使 ServletContext 生效,需要在web.xml 中配置监听器,并且web.xml 把它放在正确的WEB-INF/classes目录下,

 

[html] view plain copy
 
    1. <listener>  
    2.     <listener-class>MyServletContextListener</listener-class>  
    3. </listener>  
posted @ 2018-03-27 16:28  洪福必成  阅读(223)  评论(0编辑  收藏  举报