第七章监听器Listener--八种不同的Listener学习笔记

        Listener用于监听Java Web程序中的事件,例如创建、修改、删除Session、request、context等,并触发相应的时间。
        使用Listener需要实现相应的Listener接口。应该触发Listener事件的时候,Tomcat会自动调用Listener方法。
        Servlet 2.5规范中共有8种Listener,分别用于监听Session、context、request等的创建销毁属性变化等。另一个Listener能够监听存放在Session中的对象。共有6中event。
监听对象的创建与销毁
        HttpSessionListener:监听Session的创建销毁。创建Session时执行sessionCreated(HttpSessionEvent se)方法。超市或者执行session.invalidate()时执行sessionDestroyed(HttpSessionEvent se)方法。该Listener可用于收集在线者信息
        ServletContextListener:监听context的创建与销毁。context代表当前的web应用程序。服务器启动或者热部署war包时执行contextInitialiaed(ServletContextEvent event)方法。服务器关闭时或者只关闭该web时会执行contextDestroyed(ServletContextEvent event)方法。该Listener可用于启动时获取web.xml里配置的初始化参数
        ServletRequestListener:监听request的创建与销毁。用户每次请求request都会执行requestInitialized(ServletRequestEvent enent)方法。request处理完毕自动销毁前执行requestDestroy(ServletRequestEvent event)方法。注意如果一个Html页面含有多个图片,则请求一次HTML页面可能会触发多次request事件。
监听对象的属性变化
        这类Listener用于监听Session、context、request的属性的变化,接口方式为xxxAttributeListener,包括HttpAttributeListener、ServletContextListener、ServletRequestListener。当被监听对象中添加、更新、移除属性时,会分别执行xxxAdded(),xxxReplace(),xxxRemoved方法,xxx分别代表Session、context、request。
监听Session内的对象
        除了上面的6种Listener,还有两种Listener用于监控Session内的对象,分别是HttpSessionBindingListener与HttpSessionActivationListener。
        HttpSessionBindingListener:当对象被放到Session里时执行valueBound(HttpSessionBindEvent event)方法。当对象被从Session里移除时执行valueUnbound(HttpSessionBindingEvent event)方法。
        HttpSessionActivationListener:当服务器关闭时,会将Session内容保存硬盘上,这个过程叫钝化,调用sessionWillPassivate(HttpSessionEvent se)方法,当对象被重新加载是,调用sessionDidActivate(HttpSessionEvent se)方法。
        这两个Listener与上面的六种不同,这两个监听的是Session中的对象而非Session,所以不需要在web.xml中配置
                                                                                                                                       菜包子
                                                                                                                        2013年6月8日0:40:33 于宿舍

posted on 2013-06-08 00:43  菜包子  阅读(498)  评论(0编辑  收藏  举报

导航