浅析servlet的ServletContextListener与Spring的ApplicationListner

本文深入解析了Java Web中的ServletContextListener和Spring的ApplicationListener。首先介绍了监听器的概念,如HttpSessionListener、ServletContextListener和ApplicationListener的用途。接着详细阐述了如何创建和添加ServletContextListener,以及测试运行的过程。然后讨论了Spring的启动过程,特别是ContextLoaderListener在contextInitialized方法中的作用。最后,文章通过实例展示了如何创建并响应ContextRefreshedEvent事件以及自定义事件监听器。
摘要由CSDN通过智能技术生成

1. 简单剖析JSPsessionappliactioon创建过程

JSP中使用的sessionapplicationpageContext的创建其实是在Servlet容器中实现的,JSP页面被在Servlet容器中会被转换为HttpServlet的一个子类(tomcat为例,转换后的文件存储在apache-tomcat-*\work\Catalina\[项目IP]\[项目名称 ]\org\apache\jsp

通过如下代码截图可以看出去

Ø  applicationjavax.servlet.ServletContext实例,通过pageContext.getServletContext()获取

Ø  sessionjavax.servlet.http.HttpSession实例,通过pageContext.getSession()获取

 

详细内容可以通过JSP运行原理以及执行过程源码分析了解

2. Java Web ×××Listener概述

监听器是典型的观察者设计模式的实现

Servletspring中我们熟知的listeners包括HttpSessionListenerServletContextListenerApplicationListener

Ø HttpSessionListener是对javax.servlet.http.HttpSessionsession)的监听

Ø ServletContextListener是对javax.servlet.ServletContext(application)的监听

Ø ApplicationListener是对SpringApplicationContext的监听。

 

这些监听接口的监听方法会在它们所监听的内容状态发生变化时被调用,这些被监听的内容(sessionapplication)在服务器启动时创建,在服务器关闭时销毁,所以就可以在对应的监听方法中实现系统的一系列初始化配置动作(后面会举例介绍)。

这些Listeners接口中都会有对应状态的监听方法,例如ServletContextListener

Ø  publicvoid contextInitialized(ServletContextEventcontextEvent)ServletContext创建时被调用

Ø  publicvoidcontextDestroyed(ServletContextEvent contextEvent)ServletContext被销毁时调用

 

3. ServletContextListener

3.1.   创建监听器类

MyServletContextListener.java

@Component("myServletContextListener")

public class MyServletContextListener implements ServletContextListener {

   private Loggerlogger = LogManager.getLogger(MyServletContextListener.class);

   @Override

   publicvoidcontextInitialized(ServletContextEvent arg0) {

      logger.debug("ServletContext初始化开始");

      logger.debug("一系列初始化操作......");

   }

   @Override

   publicvoidcontextDestroyed(ServletContextEvent arg0) {

      logger.debug("ServletContext销毁");

      logger.debug("一系列逆初始化操作......");

   }

}

 

 

3.2.   添加监听器

web.xml】加一句

<listener> 

   <listener-class>com.mlq.love.listener.MyServletContextListener</listener-class> 

</listener>

3.3.   测试运行

启动服务器,查看log如下:

 

 

3.4.   HttpSessionListener简介

MyHttpSessionListener.java

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;


public class MyHttpSessionListener implements HttpSessionListener {

   @Override

   publicvoidsessionCreated(HttpSessionEvent arg0) {

   }

   @Override

   publicvoidsessionDestroyed(HttpSessionEventarg0) {

   }

}

 

 

web.xml

<listener> 

   <listener-class>com.mlq.love.listener.MyHttpSessionListener</listener-class> 

</listener>

 

4. AppliactionListener

4.1.   Spring启动过程

Web.xml中配置如下内容

<listener>

      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

查看ContextLoaderListener源码,发现ContextLoaderListener也实现了ServletContextListener接口,在contextInitialized方法中进行Spring的相关初始化操作:

4.2.   创建(ContextRefreshedEvent事件)监听器类

4.2.1.  ContextRefreshedEvent事件发生过程

Spring框架加载完成后会publishContextRefreshedEvent事件,spring容器的许多初始化工作在ContextLoaderListener中完成,包括初始化applicationContext.xml文件中配置的bean对象、初始化国际化相关的对象(MessageSource)等,当这些步骤执行完后,最后一个就是执行刷新上下文事件,代码Trace如下

(initWebApplicationContext(event.getServletContext());
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
try {
           ...
// Initialize message source for this context.
initMessageSource();
                      
// Last step: publish corresponding event.
finishRefresh();
} catch (BeansException ex) {
// Destroy already created singletons to avoid dangling resources.
destroyBeans();

// Reset 'active' flag.
cancelRefresh(ex);

// Propagate exception to caller.
throw ex;
}
}
}

/**
* Finish the refresh of this context, invoking the LifecycleProcessor's
* onRefresh() method and publishing the
* {@link org.springframework.context.event.ContextRefreshedEvent}.
*/
protected void finishRefresh() {
// Initialize lifecycle processor for this context.
initLifecycleProcessor();

// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();

// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
}


 

 

跟进finishRefresh方法可发现publishEvent(newContextRefreshedEvent(this));这行代码,此处就是刷新上下文的事件

 

4.2.2.  创建ContextRefreshedEvent事件监听类

MyApplicationListener.java

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import org.springframework.context.ApplicationListener;

import org.springframework.context.event.ContextRefreshedEvent;

import org.springframework.stereotype.Component;

 

@Component("MyApplicationListener")

publicclassMyApplicationListenerimplements ApplicationListener<ContextRefreshedEvent> {

   Loggerlogger= LogManager.getLogger(MyApplicationListener.class);

   @Override

  publicvoidonApplicationEvent(ContextRefreshedEventevent) {

        logger.debug("监听到ContextRefreshedEvent事件");

  }

}


 

 

启动服务器,log如下:

 

4.3.   创建(自定义事件)监听器类

MyApplicationEvent.java

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import org.springframework.context.ApplicationEvent;

import org.springframework.stereotype.Component;

 

@Component("myApplicationEvent")

publicclassMyApplicationEventextends ApplicationEvent {

   Loggerlogger= LogManager.getLogger(MyApplicationEvent.class);

   privatestaticfinallongserialVersionUID= 7500024553335407309L;

   

   publicMyApplicationEvent(Object source) {

      super(source);

   }

   

   publicvoid testCustomerEvent(){

      logger.debug("自定义事件被触发");

   }

}

 


 

 

 

MyCustomerApplicationListener.java

publicclassMyCustomerApplicationListenerimplements ApplicationListener {

   @Override

   publicvoidonApplicationEvent(ApplicationEvent event) {

      if(eventinstanceofMyApplicationEvent){

         MyApplicationEventmyEvent = (MyApplicationEvent)event;

         myEvent.testCustomerEvent();

      }

   }

 

}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱清清

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值