1.首先来看一看源码 该类的源码
-
public interface ServletContextListener extends EventListener {
-
-
/**
-
* Receives notification that the web application initialization
-
* process is starting.
-
*
-
* <p>All ServletContextListeners are notified of context
-
* initialization before any filters or servlets in the web
-
* application are initialized.
-
*
-
* @param sce the ServletContextEvent containing the ServletContext
-
* that is being initialized
-
*/
-
public void contextInitialized(ServletContextEvent sce);
-
-
/**
-
* Receives notification that the ServletContext is about to be
-
* shut down.
-
*
-
* <p>All servlets and filters will have been destroyed before any
-
* ServletContextListeners are notified of context
-
* destruction.
-
*
-
* @param sce the ServletContextEvent containing the ServletContext
-
* that is being destroyed
-
*/
-
public void contextDestroyed(ServletContextEvent sce);
-
}
此接口中提供了两个方法,用于监听ServletContext 的创建和销毁,也就是监听ServletContext 的生命周期,可以说成是监听Web 应用的生命周期,当web应用启动后,就会触发ServletContextEvent 事件 当此事件执行时,就会被ServletContextListener 监听器监听到,会调用他的 contextInitialized(ServletContextEvent sce) 方法,通过sce 可以获取ServletContext 实例,初始化一些数据,例如缓存的应用,如,创建数据库连接,读取数据库数据,通过setAttribute(“”,obj) 方法设置数据,然后就是可通过servlet 获取servletContext 的实例,通过getAttribute("") 获取设置的数据
实现代码:
-
public class MyContextListener implements ServletContextListener {
-
private ServletContext context = null;
-
-
public void contextInitialized(ServletContextEvent event) {
-
context = event.getServletContext();
-
User user = DatabaseManager.getUserById(1);
-
context.setAttribute("user1", user);
-
}
-
-
public void contextDestroyed(ServletContextEvent event) {
-
User user = (User)context.getAttribute("user1");
-
DatabaseManager.updateUserData(user);
-
this.context = null;
-
}
-
}
如果是web 项目 最后一步是使 ServletContext 生效,需要在web.xml 中配置监听器,并且web.xml 把它放在正确的WEB-INF/classes目录下,
-
<listener>
-
<listener-class>MyServletContextListener</listener-class>
-
</listener>
--------------------- 本文来自 为了那份宁静 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/linhaiguo/article/details/50867376?utm_source=copy