Listener(监听器)
Listener(監聽器)
Listener簡介
- Listener是JavaWeb中三大組件之一。Servlet、Filter、Listener
- 三大組件都有的共同特點,都需要實現一個接口,并在web.xml文件配置。
- JavaWeb中的監聽器的監聽對象是誰?
- ServletContext
- HttpSession
- ServletRequest
Listener分類
- JavaWeb中的監聽器共有三種,共8個監聽器
- 生命周期監聽器,監聽三個對象的創建和銷毀的事件。
- 屬性監聽器,監聽三個對象中屬性的變化。
- session對象監聽器,將它session中的屬性,以及session的活化和鈍化。
Listener的生命周期
- ServletContextListener(ServletContext生命周期監聽器)
- void contextDestroyed(ServletContextEvent sce)
該方法在ServletContext對象銷毀前調用 - void contextInitialized(ServletContextEvent sce)
該方法在ServletContext對象創建之前調用 - ServletContextEvent.getServletContext();
ServletContextEvent 對象可以獲取到ServletContext對象
- void contextDestroyed(ServletContextEvent sce)
HttpSessionListener(HttpSession生命周期監聽器)
void sessionCreated(HttpSessionEvent se)
該方法在Session創建時調用void sessionDestroyed(HttpSessionEvent se)
在session銷毀時調用- HttpSessionEvent
可以獲取HttpSession對象
ServletRequestListener
void requestDestroyed(ServletRequestEvent sre)
在request對象銷毀時調用void requestInitialized(ServletRequestEvent sre)
在request對象創建時調用ServletRequestEvent
可以獲取ServletContext對象和ServletRequest
編寫一個監聽器的步驟:
- 1.創建一個類并實現一個接口。
- 2.在web.xml文件中注冊監聽器
屬性監聽器
屬性監聽器,監聽三個域中的屬性的變化:添加一個屬性,替換一個屬性,移除一個屬性
ServletContextAttributeListener(監聽ServletContext中的屬性的變化)
void attributeAdded(ServletContextAttributeEvent scab)
當向ServletContext中添加屬性時調用attributeRemoved(ServletContextAttributeEvent scab)
移除屬性時調用attributeReplaced(ServletContextAttributeEvent scab)
替換一個屬性時調用
- HttpSessionAttributeListener
- void attributeAdded(HttpSessionBindingEvent se)
- void attributeRemoved(HttpSessionBindingEvent se)
- void attributeReplaced(HttpSessionBindingEvent se)
- HttpSessionBindingEvent
- 1.可以獲取到屬性名 getName()
- 2.可以獲取屬性的舊值 getValue()
- 3.可以獲取到HttpSession對象 getSession();
- ServletRequestAttributeListener
- void attributeAdded(ServletRequestAttributeEvent srae)
- void attributeRemoved(ServletRequestAttributeEvent srae)
- void attributeReplaced(ServletRequestAttributeEvent srae)
兩個監聽器監聽session域中的屬性
- HttpSessionBindingListener
監聽session域中某一個類的實例的添加和移除。
該接口由JavaBean來實現,不需要再web.xml文件配置- valueBound(HttpSessionBindingEvent event)
當該類的實例,作為屬性設置進session域中時調用 - valueUnbound(HttpSessionBindingEvent event)
當該類的實例,從session域中被移除時調用
- valueBound(HttpSessionBindingEvent event)
HttpSessionActivationListener
監聽session域中的某類屬性,和session一起活化和鈍化的事件。
該接口由JavaBean來實現,同樣不需要再web.xml中配置- void sessionDidActivate(HttpSessionEvent se)
當前對象和session一起被活化到內存時調用 - void sessionWillPassivate(HttpSessionEvent se)
當前對象和session一起鈍化到硬盤時調用
- void sessionDidActivate(HttpSessionEvent se)
轉載于:https://www.cnblogs.com/mazhitao/p/7440655.html
總結
以上是生活随笔為你收集整理的Listener(监听器)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】Spring事务超时时间可能存在的
- 下一篇: Sleep()和wait()方法的区别