Listener-概述
Listener:监听器
概念:web的三大组件之一
事件:一件事情
事件源:事件发生的地方
监听器:一个对象
注册监听:将事件,事件源,监听器绑定在一起。当事件源上发生某个事件后,执行监听器代码
ServletContextListener:监听ServletContext对象的创建和销毁
void contextDestroyed(ServletContextEvent sce):ServletContext对象被销毁之前会调用该方法
void contextInitialzed(ServletContextEvent sce):ServletContext对象创建后调用该方法
Listener-ServletContextListener使用
步骤:
1.定义一个类,实现ServletContextListener接口
2.复写方法
3.配置
1.web.xml
<listener>
<listener-class>com.example.listener.ContextLoaderListener</listener-class>
</listener>
指定初始化参数<context-param>
2.注解:
@WebListener
创建ContextLoaderListener类
package com.example.listener; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import java.io.FileInputStream; @WebListener public class ContextLoaderListener implements ServletContextListener { /** * 监听ServletContext对象创建的,ServletContext对象服务器启动后自动创建 * @param sce */ @Override public void contextInitialized(ServletContextEvent sce) { // 加载资源文件 // 获取ServletContext对象 ServletContext servletContext = sce.getServletContext(); // 记载资源文件 String initParameter = servletContext.getInitParameter("contextConfigLocation"); // 获取真实路径 String realPath = servletContext.getRealPath(initParameter); // 加载进内存 try { FileInputStream fileInputStream = new FileInputStream(realPath); System.out.println(fileInputStream); } catch (Exception e) { e.printStackTrace(); } System.out.println("ServletContext对象被创建"); } /** * 在服务器关闭后,ServletContext对象被销毁,当服务器正常关闭后该方法被盗用 * @param sce */ @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("ServletContext对象被销毁了"); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- <filter> <filter-name>demo1</filter-name> <filter-class>com.example.filter.FilterDemo1</filter-class> </filter> <filter-mapping> <filter-name>demo1</filter-name> <!– 拦截路径–> <url-pattern>/*</url-pattern> <!– <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>ERROR</dispatcher> <dispatcher>ASYNC</dispatcher>–> </filter-mapping>--> <!-- 配置监听器 --> <!--<listener> <listener-class>com.example.listener.ContextLoaderListener</listener-class> </listener>--> <!-- 指定初始化参数 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/applicationContext.xml</param-value> </context-param> </web-app>
applicationContext.xml
<?xml version="1.0" encoding="utf-8" ?> <bean></bean>标签:ServletContextEvent,ServletContextListener,sce,Listener,概述,ServletContext,import From: https://www.cnblogs.com/wsfj/p/17118987.html