01 ServletContext相关监听器

ServletContextListener:

主要用于监听ServetContext对象的创建和销毁。
ServletContext对象:代表整个web应用。
创建:web应用加载
销毁:web应用重新加载或web服务停止。
步骤:

  1. 创建java类,实现ServletContextListener接口,实现其中的方法
  1. 监听器要交给tomcat服务器运行。

需要在web.xml文件中进行配置



    
    com.xxjqr.servlet_study.listener.MyContextListener

ServletContextAttributeListener:

用于监听ServletContext对象的属性操作(增加属性,修改属性,删除属性)
增加属性: setAttribute(name,Object); 第一次就是增加属性
修改属性: setAttribute(name,Object); 如果前面有增加了同名的属性,则修改。
删除属性: removeAttribute(name);

/**
 * ServletContext的监听器
 *  1)在项目启动的时候,初始化表
 *  2)在项目结束的时候,删除表
 */
public class MyContextListener implements ServletContextListener,ServletContextAttributeListener{

    SystemDao dao = new SystemDao();
    /**
     * 该方法用于监听ServletContext对象的创建行为
     */
    public void contextInitialized(ServletContextEvent sce) {
        /*当该web项目创建的运行的时候,会调用该方法*/
        System.out.println("初始化成功");
    }

    /**
     * 该方法用于监听ServletContext对象的销毁行为
     */
    public void contextDestroyed(ServletContextEvent sce) {
        /*当停止项目或重新部署项目时会调用*/
        System.out.println("清除成功");
    }
    
    
    /*********************属性相关的**************************/
    
    
    /**
     * 属性增加
     */
    public void attributeAdded(ServletContextAttributeEvent scab) {
        //System.out.println("属性增加");
        //得到属性名
        String name = scab.getName();
        //得到属性值
        Object value = scab.getValue();
        System.out.println("属性增加: "+name+"="+value);
    }

    /**
     * 属性修改
     */
    public void attributeReplaced(ServletContextAttributeEvent scab) {//ServletContextAttributeEvent已经包含了事件源对象
        //System.out.println("属性修改");
        String name = scab.getName();
        //得到修改前的属性值
        //Object value = scab.getValue();
        
        //得到修改后的属性值
        //需要从ServletContext事件源对象再次获取属性,才可以得到最新的属性值。
        ServletContext context = scab.getServletContext();
        Object value = context.getAttribute(name);
        
        System.out.println("属性修改: "+name+"="+value);
    }
    /**
     * 属性删除
     * @param scab
     */
    public void attributeRemoved(ServletContextAttributeEvent scab) {
        //System.out.println("属性删除");
        
        String name = scab.getName();
        //得到属性值
        Object value = scab.getValue();
        System.out.println("属性删除: "+name+"="+value);
    }
    
}

你可能感兴趣的:(01 ServletContext相关监听器)