Servlet中的Listener

在整个Tomcat服务器中,Listener使用得非常广泛,它是基于观察者模式设计的,Listener的设计为开发Servlet应用程序提供了一种快捷的手段,能够方便地从另一个纵向维度控制程序和数据。目前在Servlet中提供了6种两类事件的观察者接口,它们分别是:EventListener类型的ServletContextAttributeListener、ServletRequestAttributeListener、ServletRequestListener、HttpSessionAttributeListener和LifecycleListener类型的ServletContextListener、HttpSessionListener。

输入图片说明

他们基本涵盖了整个Servlet生命周期中你最感兴趣的每种事件。这些Listener的实现类可以配置在web.xml文件的<listener/>标签中。当然也可以在应用程序中动态添加Listener,需要注意的是ServletContextListener在容器启动之后就不能再添加新的,因为它所监听的事件已经不会再出现了。

如Spring的org.springframework.web.context.ContextLoaderListener就实现了一个ServletContextListener,当容器加载时启动Spring容器。ContextLoaderListener在contextInitialized方法中初始化Spring容器,有几种办法可以加载Spring容器,通过在web.xml的<context-param>标签中配置Spring的applicationContext.xml的路径,文件名可以任意取,如果没有配置,将在/WEB-INF/路径下查找默认的applicationContext.xml文件。ContextLoaderListener的contextInitialized方法代码如下。

public void contextInitialized(ServletContextEvent event){
    this.contextLoader = createContextLoader();
    if(this.contextLoader == null){
        this.contextLoader = this;   
    }
    this.contextLoader.initWebApplicationContext(event.getServletContext());
}

转载于:https://my.oschina.net/chenxuanli/blog/1531281

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值