Listener是基于观察者模式设计的,Listener为Servlet应用程序提供一种控制程序和数据的手段。
Listener的注册
Java Web的listener注册比较简单,因为其监听的对象及事件都是Servlet容器创建的,如果需要它们的监听器的话,只需要在web.xml中配置即可:
<!-- web.xml-->
<listener>
<listener-class>... ...实现特定接口的自定义监听器1</listener-class>
<listener-class>... ...实现特定接口的自定义监听器2</listener-class>
... ...
</listener>
对于多个实现相同接口的listener,在执行时按照在web.xml中注册的顺序来决定。
listener也可以在应用程序中动态添加。
Listener相关接口
Servlet规范中定义了多种类型的listener,它们用于监听的事件源分别为ServletContext,HttpSession和ServletRequest这三个域对象。
Servlet规范针对这三个对象上的操作,又把这写监听器分为三种类型:
- 监听三个域对象的创建和销毁的事件监听器
Listener类 | 含有的接口 | 接口说明 |
ServletContextListener | contextInitialized(ServletContextEvent sce);
contextDestroyed(ServletContextEvent sce); | Context容器初始化时触发,在所有的Filter和Servlet的init方法调用之前contextInitialized接口先被调用;
Context容器销毁,在所有的Filter和Servlet的destroy方法调用之后contextDestroyed接口被调用; |
HttpSessionListener | SessionCreated(HttpSessionEvent se); | 当一个session对象被创建时触发; |
ServletRequestListener | requestInitialized(ServletRequestEvent sre); | 当HttpServletRequest对象被传递到用户的Servlet的service方法之前该方法被触发; |
注意:ServletContextListener在容器启动之后就不能再添加新的了,因为它所监听的事件已经不会再出现了。
- 监听三个域对象中属性的增,删,改的事件监听器
Listener类 | 含有的接口 | 接口说明 |
ServletContextAttributeListener | AttributeAdded(ServletContextAttributeEvent scab);
| 当调用servletContext.setAttribute方法时触发这个方法;
当调用servletContext.removeAttribute方法时触发这个方法;
如果在调用servletContext.setAttribute之前该attribute已经存在,则替换这个attribute时,这个方法被触发 |
HttpSessionAttributeListener | attributeAdded(HttpSessionBindingEvent se);
attributeRemoved(HttpSessionBindingEvent se);
attributeReplaced(HttpSessionBindingEvent se); | session.setAttribute方法被调用时该方法被触发;
session.removeAttribute方法被调用时该方法被触发;
如果在调用session.setAttribute之前该attribute已经存在,则替换这个attribute时这个方法被触发; |
ServletRequestAttributeListener | AttributeAdded(ServletRequestAttributeEvent srae);
AttributeRemoved(ServletRequestAttributeEvent srae);
AttributeReplaced(ServletRequestAttributeEvent srae); | 当调用request.setAttribute方法时触发这个方法;
当调用request.removeAttribute方法时触发这个方法;
如果在调用request.setAttribute之前该attribute已经存在,则替换attribute时这个方法被触发; |
- 感知型监听器
这种监听器不需要注册。
某个java bean实现这个接口后就可以监听何时被绑定,解绑或被激活或钝化。
HttpSessionBindingListener:实现该接口的类,能检测自己何时被HttpSession绑定,解绑;
HttpSessionActivationListener:实现该接口的类,能检测自己何时随着HttpSession一起激活和钝化;
Listener的应用示例
比如:
- 应用的初始化工作 —— 在自定义继承的ServletContextListener监听器的contextInitialized方法中,进行应用级的资源初始化以便提高效率,在contextDestroyed方法中对应用级的资源进行释放;