目录
1、Listener的概念
Listener(监听器)是web的三大组件之一。
事件监听机制:
- 事件:一件事情。
- 事件源:事件发生的地方。
- 监听器:一个对象。
- 注册监听:将事件、事件源、监听器绑定在一起。当事件源上发生某个事件后,执行监听器代码。
2、监听器Listenter类
2.1、ServletContextListener
ServletContextListener:监听ServletContext对象的创建和销毁。
1、方法:
-ServletContext对象被销毁之前会调用该方法:
void contextDestroyed(ServletContextEvent sce);
-ServletContext对象创建后会调用该方法:
void contextInitialized(ServletContextEvent sce);
2、使用监听器的步骤:
1)定义一个类,实现ServletContextListener接口;
2)重写方法;
3)配置:
① web.xml;
<listener>
<listener-class>
com.my.web.listener.ContextLoaderListener
</listener-class>
</listener>
指定初始化参数:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
② 注解:
@WebListener
package com.clp.web.listener;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@WebListener
public class ContextLoaderListener implements ServletContextListener {
/**
* 监听ServletContext对象的创建。(ServletContext对象在服务器启动后会创建)
* 在服务器启动后自动调用
*/
public ContextLoaderListener(ServletContextEvent sce) {
// //加载资源文件
// //1、获取ServletContext对象
// ServletContext servletContext = sce.getServletContext();
//
// //2、加载资源文件
// /**
// * 在web.xml中可以指定资源文件路径:
// * <context-param>
// * <param-name>contextConfigLocation</param-name>
// * <param-value>WEB-INF/classes/applicationContext.xml</param-value>
// * </context-param>
// */
// String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
//
// //3、获取真实路径
// String realPath = servletContext.getRealPath(contextConfigLocation);
//
// //4、加载进内存
// try {
// FileInputStream fis = new FileInputStream(realPath);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
System.out.println("ServletContext对象被创建了..");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
/* This method is called when the servlet context is initialized(when the Web application is deployed). */
}
/**
* 在服务器关闭后,ServletContext对象被销毁。
* 当服务器正常关闭后该方法被调用
*
* @param sce
*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
/* This method is called when the servlet Context is undeployed or Application Server shuts down. */
System.out.println("ServletContext对象被销毁了..");
}
}