--Listener (一)Listener简介

来源:互联网 发布:java单例模式双重锁 编辑:程序博客网 时间:2024/06/05 03:05

Listener简介

Listener是javaweb中一个重要的组件,它的主要作用使用来监听域对象(ServletContext,ServletRequest,httpSession)的生命周期和属性变化。例如,web应用被加载的时候可以做一些初始化工作,加载数据库连接池,获取初始化信息之类的;当请求,session创建销毁的时候添加我们自己的逻辑;在属性改变的时候,监听改变。

事件源和事件对象

事件源

主要是三大事件源,包括ServletContext,ServletRequest,HttpSession,对三大事件源的生命周期和属性监听。

1.ServletContextListener(监听生命周期)        监听ServletContext        创建ServletContext时,调用contextInitialized (ServletContextEvent sce)方法;        销毁ServletContext时,调用contextDestroyed(ServletContext- Event sce)方法。2.ServletContextAttributeListener(监听属性变化)        监听servletContext的属性变化(添加,删除,替换)。        attributeAdded(ServletContextAttributeEvent event)         attributeRemoved(ServletContextAttributeEvent event)         attributeReplaced(ServletContextAttributeEvent event) 3.ServletRequestListener(监听生命周期)        创建ServletContext时,调用contextInitialized (ServletContextEvent sce)方法;        销毁ServletContext时,调用contextDestroyed(ServletContext- Event sce)方法。4.ServletRequestAttributeListener(监听属性变化)        监听ServletRequest的属性变化(添加,删除,替换)        attributeAdded(ServletRequestAttributeEvent srae)         attributeRemoved(ServletRequestAttributeEvent srae)         attributeReplaced(ServletRequestAttributeEvent srae) 5..HttpSessionListener(监听生命周期)        监听HttpSession        创建一个Session时,调用session Created (SessionEvent se)方法;        销毁一个Session时,调用sessionDestroyed (HttpSessionEvent se)方法。6.HttpSessionAttributeListener(监听属性变化)        监听HttpSession属性的变化        attributeAdded(HttpSessionBindingEvent event)         attributeRemoved(HttpSessionBindingEvent event)         attributeReplaced(HttpSessionBindingEvent event) 

事件对象

事件对象包含:

ServletContextEvent:    ServletContext getServletContext()HttpSessionEvent:    HttpSession getSession()ServletRequest:    ServletContext getServletContext();    ServletReques getServletRequest();ServletContextAttributeEvent    String getName():获取当前操作的属性名;    Object getValue():获取当前操作的属性值;    ServletContext getServletContext():获取ServletContext对象。HttpSessionBindingEvent    String getName():获取当前操作的属性名;    Object getValue():获取当前操作的属性值;    HttpSession getSession():获取当前操作的session对象。ServletRequestAttributeEvent    String getName():获取当前操作的属性名;    Object getValue():获取当前操作的属性值;    ServletContext getServletContext():获取ServletContext对象;    ServletRequest getServletRequest():获取当前操作的ServletRequest对象。

使用监听器

使用监听器大概包含:
1. 编写一个java类,实现对应的监听器接口。
2. 在监听器接口的方法中实现我们自己的程序逻辑。
3. 在web.xml中注册listener.

0 0
原创粉丝点击