Listener 与 Event

撰写过AWT或Swing的Java程序设计人员对于Listener与Event应该并不陌生,实现 Listener的类可以在特定事件发生时,调用特定的方法来对事件进行回应,在编写JSP/Servlet应用程序时,也有类似的Listener接 口与Event类,所不同的是在AWT或 Swing中是向特定组件加入Listener,而在JSP/Servlet中则是在web.xml中注册Listener,由Container在特定事件发生时调用特定的实现Listener类。

至JSP 2.0/Servlet 2.4为止,共有八个Listener接口,以及六个Event类。

ServletContextListener接口有两个必须实现的方法,contextInitialized()与 contextDestroyed(),它们接收ServletContextEvent事件,在Container载入Web应用程序时(例如启动 Container之后),会调用contextInitialized(),而当容器移除Web应用程序时,会调用contextDestroyed ()方法。

ServletContextAttributeListener接口有三个必须实现的方法,attributeAdded()、 attributeReplaced()、attributeRemoved(),它们接收ServletContextAttributeEvent事件,若有对象加入为application(ServletContext)对象的属性,则会调用attributeAdded(),同理在置换属性与移除属性时,会分别调用attributeReplaced()、attributeRemoved()。

HttpSessionListener接口有两个必须实现的方法,sessionCreated()与sessionDestroyed (),它们接收HttpSessionEvent事件,与ServletContextListener接口类似,在session (HttpSession)对象建立或被消灭时,会分别调用这两个方法。

HttpSessionAttributeListener接口有三个必须实现的方法,attributeAdded()、 attributeReplaced()、attributeRemoved(),它们接收HttpSessionBindingEvent事件,与 ServletContextAttributeListener接口类似,若有对象加入为session(HttpSession)对象的属性,则会呼叫attributeAdded(),同理在置换属性与移除属性时,会分别调用attributeReplaced()、 attributeRemoved()。

HttpSessionActivationListener接口有两个必须实现的方法,sessionDidActivate()与 sessionWillPassivate(),它们接收HttpSessionEvent,Activate与Passivate是用于置换对象的动作,当session对象为了资源利用或负载平衡等原因而必须暂时储存至硬碟或其它储存器时(透过对象序列化),所作的动作称之为Passivate,而硬盘或储存器上的session对象重新载入JVM时所采的动作称之为Activate,所以容易理解的,sessionDidActivate()与 sessionWillPassivate()分别于Activeate后与将Passivate前调用。

ServletRequestListener接口有两个必须实现的方法,requestInitialized()与 requestDestroyed(),它们接收RequestEvent事件,与ServletContextListener接口类似,在 request(HttpServletRequest)对象建立或被消灭时,会分别调用这两个方法。

ServletRequestAttributeListener接口有三个必须实现的方法,attributeAdded()、 attributeReplaced()、attributeRemoved(),它们接收HttpSessionBindingEvent事件,与 ServletContextAttributeListener接口类似,若有对象加入为request(HttpServletRequest)对象的属性,则会调用attributeAdded(),同理在置换属性与移除属性时,会分别调用attributeReplaced()、 attributeRemoved()。

实现以上这几个接口的类,必须在web.xml中向容器注册,容器才会在对应的事件发生时调用对应的类,例如:

<listener>
    <listener-class>
      demo.servlet.listener.CustomServletContextListener
    </listener-class>

</listener>


另外还有一个HttpSessionBindingListener接口,它使用的方法不同,拥有两个必须实现的方法, valueBound()与valueUnbound(),接收的参数为HttpSessionBindingEvent,实现 HttpSessionBindingListener接口的类,其实例如果被加入至session(HttpSession)对象的属性中,则会调用 valueBound(),如果被从session(HttpSession)对象的属性中移除,则会调用valueUnbound(),实现 HttpSessionBindingListener接口的类不需在web.xml中设定。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值