资源预览内容
第1页 / 共21页
第2页 / 共21页
第3页 / 共21页
第4页 / 共21页
第5页 / 共21页
第6页 / 共21页
第7页 / 共21页
第8页 / 共21页
第9页 / 共21页
第10页 / 共21页
亲,该文档总共21页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述
第7章 监听器Listener Java Web程序设计基础7.1 Listener概述n什么是Listener nListener的使用7.1.1 什么是Listener nWeb应用程序员可以利用Listener接 口,监听在Container中某一个执行程 序,并且根据其应用程序的需求做出 适当的响应7.1.2 Listener的使用n使用Listener需要实现相应的 Listener接口 nListener需要在web.xml中配置才生效 7.2 Listener的分类n监听对象的创建与销毁 n实例:监听Session、Request与 ServletContextn监听对象的属性变化 n监听Session内的对象 Listener 接口简介Listener 接口简介Listener接口Event类ServletContextListenerServletContextEventServletContextAttributeListe nerServletContextAttributeEventHttpSessionListenerHttpSessionEventHttpSessionActivationListen er HttpSessionBindingListenerHttpSessionBindingEventHttpSessionAttributeListenerServletRequestListenerServletRequestEventServletRequestAttributeListe nerServletRequestAttributeEven t7.2.1 监听对象的创建与销毁 nHttpSessionListener: 监听Session的创建与销毁nServleContextListener: 监听Context的创建与销毁nServletRequestListener: 监听request的创建与销毁 HttpSessionListenern和ServletContextListener接口类似 ,当有Session产生或是消失,会自动 调用:sessionCreated和sessionDestroyed方法ServletContextListenern一个实现ServletContextListener接 口的程序,当Container启动时,程序 会自动开始监听的工作,它首先会调 用contextInitialized()接收对应的 javax.servlet.ServletContextEvent 事件ServletRequestListenernServletRequestListener是Servlet 2.4的新功能n该接口和ServletContextListener接 口类似,当有请求产生或消失,会自 动调用requestInitialized()和 requestDestroyed().7.2.2 实例:监听Session、Request与ServletContextnJava中的类可以实现多个接口,因此 实现Listener时可以用一个类实现多 个Listener接口。这样的好处是多种 Listener一块儿工作,使用同一个类 的资源 public class ListenerTest implements HttpSessionListener, ServletContextListener, ServletRequestListener 7.2.3 监听对象的属性变化 nListener用于监听session、request 、context的属性变化 ServletContextAttributeListenerHttpSessionAttributeListenerServletRequestAttributeListener ServletContextAttributeListenern一个实现 ServletContextAttributeListener接 口的程序,它能够监听Application范 围的变化HttpSessionAttributeListenern和ServletContextAttributeListener接口 类似,只不过该接口是监听Session范围的 变化的nHttpSessionAttributeListener和 HttpSessionBindingListener两个功能很 相似,但是也有一些不同点:HttpSessionAttributeListener需要在web.xml 中设定。HttpSessionAttributeListener监听web站点所 有Session范围的变化;而 HttpSessionBindingListener只单纯监听实现 它的类ServletRequestAttributeListenernServletRequestAttributeListener也 是Servlet2.4的新功能n该接口和 ServletContextAttributeListener接 口功能相似,只不过该接口监听 Request范围的变化7.2.4 监听Session内的对象 n主要包括:HttpSessionBindingListenerHttpSessionActivationListenerHttpSessionBindingListenern当我们实现这个接口后,只要对象加 入Session范围或从Session范围中移 除时,Container分别会自动调用下列 两个方法:valueBound(HttpSessionBindingEvent event)valueUnbound(HttpSessionBindingEvent event)HttpSessionActivationListenern该接口主要用于:同一个Session转移至不 同JVM的情形,例如:负载平衡(Load Balancing)机制。n当Session被存储起来,并且等待转移至另 一个JVM,这段时间成为失效状态,若 Session中的属性对象实现该接口时, Container会自动调用 sessionWillPassivate方法,通知该对象 的Session已变为失效状态。当Session转 移至其他JVM后,它又成为有效状态,此时 Container会自动调用sessionDiaActivate 方法7.3 Listener使用案例n单态登录 n显示在线用户 Q&A这是我,我是JWShock?
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号