JavaWeb-监听器

一.监听器

  1.JavaWeb中有三大组件:Servlet,Listener,Filter

  2.最开始接触监听器时是在JavaSE的awt,现在讲的是JavaWeb中的应用

  3.它是一个接口,需要我们来实现

  4.在Web中是需要注册的,在web.xml中,不过注册比Servlet简单多了

  5.监听器可以监听对象是否发生某个事件,并调用特定的方法;即监听器也是处理器;

二.观察者

  1.事件源:参与事件的对象

  2.事件:比如点击事件

  3.监听器:监听事件源是否发生事件

三.JavaWeb监听器

  1.Web监听器监听的是三大域:ServletContext,HttpSession,ServletRequest

  2.三大域中各个域都有两个特有的监听器:生命周期监听(生死监听)和属性监听,他们的命周期监听和属性监听所表达的意思相同

  3.ServletContext

    >生命周期监听:ServletContextListener

      方法:contextInitialized(ServletContextEvent sce),ServletContext创建后马上调用,参数为事件对象,可以获取到事件源

         contextDestroyed(ServletContextEvent sce),ServletContext销毁前马上调用,参数为事件对象,可以获取到事件源

    >属性监听:ServletContextAttributeListener

      方法:attributeAdded(ServletContextAttributeEvent event),添加属性时调用

         attributeRemoved(ServletContextAttributeEvent event),移除属性时调用

         attributeReplaced(ServletContextAttributeEvent event),修改属性时调用,注意的参数事件对象的getValue()获取的时老值,而不是新值

  4.HttpSession

    >生命周期监听:HttpSessionListener

      方法:sessionCreated(HttpSessionEvent se),HttpSession创建后马上调用,参数为事件对象,可以获取到事件源

         sessionDestroyed(HttpSessionEvent se),HttpSession销毁前马上调用,参数为事件对象,可以获取到事件源

    >属性监听:HttpSessionAttributeListener

      方法:attributeAdded(HttpSessionBindingEvent event),添加属性时调用

         attributeRemoved(HttpSessionBindingEvent event),移除属性时调用

         attributeReplaced(HttpSessionBindingEvent event),修改属性时调用,注意的参数事件对象的getValue()获取的时老值,而不是新值

  5.ServletRequest

    >生命周期监听:ServletRequestListener

      方法:requestInitialized(ServletRequestEvent sre),ServletRequest创建后马上调用,参数为事件对象,可以获取到事件源

         requestDestroyed(ServletRequestEvent sre),ServletRequest销毁前马上调用,参数为事件对象,可以获取到事件源

    >属性监听:ServletRequestAttributeListener

      方法:attributeAdded(ServletRequestAttributeEvent srae),添加属性时调用

         attributeRemoved(ServletRequestAttributeEvent srae),移除属性时调用

         attributeReplaced(ServletRequestAttributeEvent srae),修改属性时调用,注意的参数事件对象的getValue()获取的时老值,而不是新值

四.感知监听

  1.感知监听并不是监听三大域,它监听的是JavaBean对象,而且跟httpSession相关

  2.感知监听不需要注册

  3.感知监听有两个:

    >HttpSessionBindingListener(监听bean有没有被添加到session域或从sesion中移除)

      (1)我们需要让JavaBean类去实现该监听器接口,就相当于bean自己监听自己跟session的状态关系

      (2)有如下两个方法:

          * valueBound(HttpSessionBindingEvent event),当bean对象被添加到session域中,调用该方法

          * valueUnbound(HttpSessionBindingEvent event),当bean对象被移除到session域中,调用该方法

    >HttpSessionActivationListener(监听bean有没有随session钝化或活化)

      (1)需要让JavaBean类去实现该监听器接口

      (2)有如下两个方法:

          *  sessionWillPassivate(HttpSessionEvent se),当该bean对象随session钝化后立即调用的方法

          * sessionDidActivate(HttpSessionEvent se),当该bean对象随session活化后立即调用的方法

      (3)注意的是:添加在session域中的对象必须是实现了序列化接口Serializable,不然无法钝化到硬盘上

.监听器注册格式

   1.到web.xml注册,如图:

      

原文地址:https://www.cnblogs.com/ibcdwx/p/12502758.html