日期:2014-05-19  浏览次数:20698 次

【转】J2EE监听器和过滤器基础

Servlet程序由Servlet,Filter和Listener组成,其中监听器用来监听Servlet容器上下文。

监听器通常分三类:基于Servlet上下文的ServletContex监听,基于会话的HttpSession监听和基于请求的ServletRequest监听。

?

  • ServletContex监听器
ServletContex又叫application,存在范围是整个Servlet容器生命周期,当系统启动时就会创建,系统关闭时会销毁,该对象通常存放一些非常通用的数据,但是不推荐存放太多,否则长期占据内存空间会影响服务器性能。
基于ServletContex的监听器可以继承两个接口并实现接口中相应的方法:
ServletContextListener接口定义了两个方法contextInitialized和contextDestroyed,分别在ServletContex创建和销毁时触发;
ServletContextAttributeListener接口定义了三个方法attributeAdded,attributeRemoved和attributeReplaced,分别在给ServletContex添加属性值,删除属性值和替换属性值时触发。
下面创建了一个基于Application的监听器:
Java代码??收藏代码
  1. ?/**?
  2. ?*?Application监听器,Servlet中的Application即ServletContext?
  3. ?*?@author?Administrator?
  4. ?*/??
  5. public?