学科分类
目录
Java Web

ServletContextListener接口

ServletContext对象是Web应用程序中一个非常重要的对象,为了监听该对象的创建与销毁过程,Servlet API中提供了一个ServletContextListener接口,当在Web应用程序中注册一个或多个实现了ServletContextListener接口的事件监听器时,Web容器在创建或销毁每个ServletContext对象时就会产生一个ServletContextEvent事件对象,然后依次调用每个ServletContext事件监听器中的处理方法,并将ServletContext事件对象传递给这些方法,来完成事件的处理工作。

ServletContextListener接口中共定义了两个事件处理方法,具体如下:

1、contextInitialized()方法

contextInitialized()方法的完整语法定义如下:

public void contextInitialized(ServletContextEvent sce)

当ServletContext对象被创建时,Web容器会调用contextInitialized()方法。contextInitialized()方法接收一个ServletContextEvent类型的参数,contextInitialized()方法内部可以通过这个参数来获取创建的ServletContext对象。

2、contextDestroyed()方法

contextDestroyed()方法的完整语法定义如下:

public void contextDestroyed(ServletContextEvent sce)

当ServletContext对象即将被销毁时,Web容器会调用contextDestroyed()方法,并将ServletContextEvent对象传递给这个方法。

点击此处
隐藏目录