您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
16_Listener_ServletContextListener使用(servlet容器创建时加载相关配置文件)
发布时间:2022-09-30 14:32:13编辑:雪饮阅读()
创建listener
如果用intellij idea的New Create Listener自动创建listener则会发现默认有可能直接实现3个接口ServletContextListener, HttpSessionListener, HttpSessionAttributeListener。
只是学习使用,则可以只实现一个接口ServletContextListener即可。其它的可以按需。
一个极简的listener:
package package3.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.io.FileInputStream;
@WebListener
public class Listener1 implements ServletContextListener{
/*
* 监听ServletContext对象创建,ServletContext对象服务器自动启动后自动创建
* 在服务器启动后自动调用
* @param servletContextEvent
* */
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
//加载资源文件
//1.获取ServletContext对象
ServletContext servletContext = servletContextEvent.getServletContext();
//2.加载资源文件
//这里获取web/WEB-INF/web.xml中web-app=>context-param=>param-name值为contextConfigLocation的context-param的param-value
//虽然这个真实路径咱们事先就准备好在src目录下applicationContext.xml(正好tomcat部署后就在WEB-INF/classes/)
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
//3.获取真实路径
String realPath = servletContext.getRealPath(contextConfigLocation);
//4.加载进内存(读取相关文件)
try{
//这里有时候会出现被加载的文件不存在的情况,可以尝试重启下intellij idea
FileInputStream fis = new FileInputStream(realPath);
System.out.println(fis);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("ServletContext对象被创建了。。。");
}
/**
* 在服务器关闭后,ServletContext对象被销毁。当服务器正常关闭后该方法被调用
* @param servletContextEvent
*/
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("ServletContext对象被销毁了。。。");
}
}
配置文件
用于加载于内存的相关配置文件,可以放在src/applicationContext.xml如:
<?xml version="1.0" encoding="UTF-8"?>
<bean></bean>
web.xml
在ServletContextListener接口的contextInitialized方法中可用来获取web/WEB-INF/web.xml中的配置(web-app下的context-param,则可以将applicationContext.xml的路径配置在web.xml中,以测试获取web.xml中的配置,也能同时测试加载applicationContext.xml到内存中)
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_3_1.xsd"
version="3.1">
<!-- 指定初始化参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
</web-app>
关键字词:Listener,ServletContextListener,servlet