一、今日内容
1. Listener概述
2. ServletContextListener监听器接口
二、Listener学习
1. Listener概述
概念:web的三大组件之一。
* 事件监听机制
* 事件 :一件事情
* 事件源 :事件发生的地方
* 监听器 :一个对象
* 注册监听:将事件、事件源、监听器绑定在一起。 当事件源上发生某个事件后,执行监听器代码
2. ServletContextListener监听器接口
ServletContextListener:是一个接口。监听ServletContext对象的创建和销毁
* 方法:
* void contextDestroyed(ServletContextEvent sce) :ServletContext对象被销毁之前会调用该方法。服务器正常关闭时会销毁对象,自动调用该方法。
* void contextInitialized(ServletContextEvent sce) :ServletContext对象创建后会调用该方法。服务器启动后会创建对象,自动调用该方法。
* 步骤:
1. 定义一个类,实现ServletContextListener接口
2. 复写方法
3. 配置
1. web.xml
<listener>
<listener-class>cn.itcast.web.listener.ContextLoaderListener</listener-class>
</listener>
* 指定初始化参数
* 在项目中把资源路径写死不太好,我们将资源路径配置到web.xml文件中,到时候只用改web.xml文件中的路径就可以了
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
2. 注解:
* @WebListener 没有括号,就是这,不用指定参数
*作用:在服务器启动时将一些资源文件加载进内存。服务器关闭时,释放内存。