1.什么是Listener监听器?
- Listener监听器是JavaWeb的三大组件之一。三大组件分别是:Servlet、Listener、Filter过滤器。
- Listener它是JavaEE的规范,就是一个接口。
- 监听器的作用是监听某种事物的变化。然后通过回调函数,反馈给客户(程序)去做一些相应的处理。
2.ServletContextListener监听器
- ServletContextListener可以监听ServletContext对象的创建与销毁。
- ServletContext对象在web工程启动的时候创建,在web工程停止的时候销毁。
- 监听到创建和销毁之后都会分别调用ServletContextListener监听器的方法反馈。
- 方法分别为:
public interface ServletContextListener extends EventListener{ /* 在ServletContext对象创建之后马上调用,做初始化。 */ public void contextInitialized(ServletContextEvent sce){ } /* 在ServletContext对象销毁之后调用 */ public void contextDestroyed(ServletContextEvent sce){ } }
3.如何使用ServletContextListener监听器监听ServletContext?
- 先写一个类去实现ServletContextListener。
- 实现其两个回调方法。
- 到web.xml中去配置监听器。