ServletContextEvent类提供有关Web应用程序Servlet上下文更改的通知。
ServletContextListener接收有关Servlet上下文更改的通知,并执行一些操作。
简而言之,每当ServletContext更改时,ServletContextEvent和ServletContextListener便会成对工作,ServletContextEvent发布一个通知,该通知由ServletContextListener接收,然后基于它执行的某些任务。
ServletContextListener接口的方法
方法 | 描述 |
---|---|
void contextDestroyed(ServletContextEvent e) | 销毁应用程序时调用。 |
void contextInitialized(ServletContextEvent e) | 在初始化应用程序时调用。 |
UserServlet.java
ContextLoaderListener.java
以上代码进一步优化:
问题:耦合高
解决:抽配置文件,解耦
web.xml
ContextLoaderListener.java
问题:耦合
解决:建一个工具类
以上只是原理分析,事实上,在Spring内部已经帮我们封装好了,Spring提供了一个监听器ContextLoaderListener封装了上述功能,该监听器内部加载Spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象。
所以我们需要做的只有两件事:
① 在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)
② 使用WebApplicationContextUtils获得应用上下文对象ApplicationContext