ServletContextListener和ContextLoaderListener用法

https://blog.csdn.net/fengshoudong/article/details/78886289

ServletContextListener接口用于tomcat启动时自动加载函数,方法如下: 
一、需加载的类必须实现ServletContextListener接口。 
二、该接口中有两个方法必须实现: 
1、contextInitialized(ServletContextEvent sce)该方法为服务器起动时加载内容。 
2、contextDestroyed(ServletContextEvent sce)该方法为服务器关闭时加载的内容。 
三、如:

public class ReadContext extends HttpServlet implements ServletContextListener{
    public void  contextInitialized(ServletContextEvent sce){
        System.out.println("this is contextInitialized");
    }
    public void contextDestroyed(ServletContextEvent sce){
        System.out.println("this is contextDestroyed");
    }
}

四、web.xml配置listener标签

<listener>
    <listener-class>ReadContext</listener-class>
</listener>

五、如果contextDestroyed不执行多是因为tomcat没有正常关闭或是没有实现ServletContextListener接口。在MyEclipse关闭tomcat的正确方法是:点击右键点关闭

六、ContextLoaderListener是spring框架中对ServletContextListener的一个实现,他会在tomcat启动时加载Spring配置。

猜你喜欢

转载自blog.csdn.net/m0_37730732/article/details/82255093