JavaWeb學習之監聽器

JavaWeb監聽器

三大組件:

Servlet

Listener

Filter

JavaWeb中的監聽器

事件源:三大域!(每個事件源都有倆類:生命週期監聽和屬性監聽)

  ServletContext

¨      生命週期監聽:ServletContextListener,它有兩個方法,一個在出生時調用,一個在死亡時調用;

  void contextInitialized(ServletContextEvent sce):創建SErvletcontext

  void contextDestroyed(ServletContextEvent sce):銷燬Servletcontext

¨      屬性監聽:ServletContextAttributeListener,它有三個方法,一個在添加屬性時調用,一個在替換屬性時調用,最後一個是在移除屬性時調用。

  void attributeAdded(ServletContextAttributeEvent event):添加屬性時;

  void attributeReplaced(ServletContextAttributeEvent event):替換屬性時;

  void attributeRemoved(ServletContextAttributeEvent event):移除屬性時;

  HttpSession

¨      生命週期監聽:HttpSessionListener,它有兩個方法,一個在出生時調用,一個在死亡時調用;

  void sessionCreated(HttpSessionEvent se):創建session

  void sessionDestroyed(HttpSessionEvent se):銷燬session

¨      屬性監聽:HttpSessioniAttributeListener,它有三個方法,一個在添加屬性時調用,一個在替換屬性時調用,最後一個是在移除屬性時調用。

  void attributeAdded(HttpSessionBindingEvent event):添加屬性時;

  void attributeReplaced(HttpSessionBindingEvent event):替換屬性時

  void attributeRemoved(HttpSessionBindingEvent event):移除屬性時

  ServletRequest

¨      生命週期監聽:ServletRequestListener,它有兩個方法,一個在出生時調用,一個在死亡時調用;

  void requestInitialized(ServletRequestEvent sre):創建request

  void requestDestroyed(ServletRequestEvent sre):銷燬request

¨      屬性監聽:ServletRequestAttributeListener,它有三個方法,一個在添加屬性時調用,一個在替換屬性時調用,最後一個是在移除屬性時調用。

  void attributeAdded(ServletRequestAttributeEvent srae):添加屬性時

  void attributeReplaced(ServletRequestAttributeEvent srae):替換屬性時

  void attributeRemoved(ServletRequestAttributeEvent srae):移除屬性時

javaWeb中完成編寫監聽器:

  寫一個監聽器類:要求必須去實現某個監聽器接口;

  註冊,是在web.xml中配置來完成註冊!

事件對象:

       1.獲取事件源對象

  ServletContextEventServletContext getServletContext()

  HttpSessionEventHttpSession getSession()

  ServletRequest

¨      ServletContextgetServletContext()

¨      ServletRequesgetServletRequest()

2.屬性事件對象除了獲取事件源對象,還能獲取屬性的名和屬性值

  ServletContextAttributeEvent

¨      ServletContextgetServletContext()

¨      StringgetName():獲取屬性名

¨      ObjectgetValue():獲取屬性值.替換時獲取的是被替換的屬性值

  HttpSessionBindingEvent:略

  ServletRequestAttributeEvent :略

 

感知監聽(都與HttpSession相關)

它用來添加到JavaBean上,而不是添加到三大域上!

這兩個監聽器都不需要在web.xml中註冊!

 

HttpSessionBindingListener:添加到javabean上,javabean就知道自己是否添加到session中了

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章