JavaWeb三大元件之Listener監聽器
一、概述
1,它是一個接口,内容由我們來實作
2,它需要注冊,例如注冊在按鈕上
3,監聽器中的方法,會在特殊事件發生時被調用
二、JavaWeb中的監聽器
1,事件源
Ø ServletContext
生命周期監聽:ServletContextListener,它有兩個方法,一個在出生時調用,一個在死亡時調用;
(1) void contextInitialized(ServletContextEvent sce):建立SErvletcontext時
(2) void contextDestroyed(ServletContextEvent sce):銷毀Servletcontext時
屬性監聽:ServletContextAttributeListener,它有三個方法,一個在添加屬性時調用,一個在替換屬性時調用,最後一個是在移除屬性時調用。
(1) void attributeAdded(ServletContextAttributeEvent event):添加屬性時;
(2) void attributeReplaced(ServletContextAttributeEvent event):替換屬性時;
(3) void attributeRemoved(ServletContextAttributeEvent event):移除屬性時;
Ø HttpSession
生命周期監聽:HttpSessionListener,它有兩個方法,一個在出生時調用,一個在死亡時調用;
(1) void sessionCreated(HttpSessionEvent se):建立session時
(2) void sessionDestroyed(HttpSessionEvent se):銷毀session時
屬性監聽:HttpSessioniAttributeListener,它有三個方法,一個在添加屬性時調用,一個在替換屬性時調用,最後一個是在移除屬性時調用。
(1) void attributeAdded(HttpSessionBindingEvent event):添加屬性時;
(2) void attributeReplaced(HttpSessionBindingEvent event):替換屬性時
(3) void attributeRemoved(HttpSessionBindingEvent event):移除屬性時
Ø ServletRequest
生命周期監聽:ServletRequestListener,它有兩個方法,一個在出生時調用,一個在死亡時調用;
(1) void requestInitialized(ServletRequestEvent sre):建立request時
(2) void requestDestroyed(ServletRequestEvent sre):銷毀request時
屬性監聽:ServletRequestAttributeListener,它有三個方法,一個在添加屬性時調用,一個在替換屬性時調用,最後一個是在移除屬性時調用。
(1) void attributeAdded(ServletRequestAttributeEvent srae):添加屬性時
(2) void attributeReplaced(ServletRequestAttributeEvent srae):替換屬性時
(3) void attributeRemoved(ServletRequestAttributeEvent srae):移除屬性時
2,JavaWeb中完成編寫監聽器
(1)寫一個監聽器類:要求必須去實作某個監聽器接口
(2)注冊,是在web.xml中配置來完成注冊;
3,事件對象
Ø ServletContextEvent:ServletContext getServletContext()
Ø HttpSessionEvent:HttpSession getSession()
Ø ServletRequest:
(1) ServletContext getServletContext();
(2) ServletReques getServletRequest();
Ø ServletContextAttributeEvent:
(1) ServletContext getServletContext();
(2) String getName():擷取屬性名
(3) Object getValue():擷取屬性值
Ø HttpSessionBindingEvent:略
Ø ServletRequestAttributeEvent :略
4,感覺監聽
1,它用來添加到JavaBean上,而不是添加到三大域上
2,這兩個監聽器都不需要再web.xml中注冊
HttpSessionBindingListener:添加到javabean上,javabean就知道自己是否添加到session中了。
HttpSessionActivationListener監聽器與HttpSessionBindingListener監聽器相似,都是感覺型的監聽器,例如讓Person類實作了HttpSessionActivationListener監聽器接口,并把Person對象添加到了session中後,當Tomcat鈍化session時,同時也會鈍化session中的Person對象,這時Person對象就會感覺到自己被鈍化了,其實就是調用Person對象的sessionWillPassivate()方法。當使用者再次使用session時,Tomcat會活化session,這時Person會感覺到自己被活化,其實就是調用Person對象的sessionDidActivate()方法。