浅析servlet的ServletContextListener与Spring的ApplicationListner

44 篇文章 1 订阅
30 篇文章 0 订阅

https://www.it610.com/article/4956002.htm

 

1. 简单剖析JSP中session、appliactioon创建过程

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

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

Ø  application是javax.servlet.ServletContext实例,通过pageContext.getServletContext()获取

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

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

浅析servlet的ServletContextListener与Spring的ApplicationListner_第1张图片

2. Java Web 的×××Listener概述

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

Servlet和spring中我们熟知的listeners包括HttpSessionListener、ServletContextListener、ApplicationListener

Ø HttpSessionListener是对javax.servlet.http.HttpSession(session)的监听

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

Ø ApplicationListener是对Spring的ApplicationContext的监听。

 

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

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

Ø  public void contextInitialized(ServletContextEventcontextEvent)在ServletContext创建时被调用

Ø  public void contextDestroyed(ServletContextEvent contextEvent)在ServletContext被销毁时调用

 

3. ServletContextListener

3.1.   创建监听器类

【MyServletContextListener.java】

@Component("myServletContextListener")

public class MyServletContextListener implements ServletContextListener {

   private Logger logger = 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(new ContextRefreshedEvent(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")
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
   Logger logger= LogManager.getLogger(MyApplicationListener.class);
   @Override
  public void onApplicationEvent(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")
public class MyApplicationEvent extends ApplicationEvent {
   Loggerlogger= LogManager.getLogger(MyApplicationEvent.class);
   private static final long serialVersionUID= 7500024553335407309L;

   public MyApplicationEvent(Object source) {
      super(source);
   }

   public void testCustomerEvent(){
      logger.debug("自定义事件被触发");
   }
}

【MyCustomerApplicationListener.java】

public class MyCustomerApplicationListenerimplements ApplicationListener {

   @Override
   public void onApplicationEvent(ApplicationEvent event) {
      if(event instanceof MyApplicationEvent){
         MyApplicationEvent myEvent = (MyApplicationEvent)event;
         myEvent.testCustomerEvent();
      }
   }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值