事件监听机制
事件:一个事情
事件源:时间发生的地方
监听器:一段对象
注册监听:将事件,事件源,监听器绑定在一起,当事件源上发生某个事件后,执行监听器事件
ServletContextListener:监听ServletContext 对象的创建和销毁
void contextDestroyed()
void contextInitialized()
步骤:
- 定义一个类,实现ServletContextListener接口
- 复写方法
- 配置
- web.xml
<!--监听器 -->
<listener>
<listener-class>com.itcast.listener.ContextDemo1</listener-class>
</listener>
指定初始化参数<context-param>
-
注解
@WebListener -
监听并初始化资源加载资源
package com.itcast.listener;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ContextDemo1 implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("ServletContextListener contextDestroyed");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
//加载资源文件
//1.获取ServletContext对象
ServletContext servletContext = sce.getServletContext();
String contextConifg = servletContext.getInitParameter("contextConifg");
//3.获取真实路径
String realPath = servletContext.getRealPath(contextConifg);
//4.加载进内存
try {
FileInputStream fileInputStream = new FileInputStream(realPath);
System.out.println(fileInputStream);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
System.out.println("ServletContextListener contextInitialized");
}
}
网友评论