servlet事件監聽器原理

這裏拿ServletContextAttributeListener來做剖析。

當我們往ServletContext裏添加一個屬性或刪除一個屬性時,有時需要做相關的操作,這時只需創建一個實現ServletContextAttributeListener的監聽器就可以了,在添加一個屬性或刪除一個屬性時就會調用這個監聽器的方法,下面是監聽器的工作原理。

WebLogic容器的WebAppServletContext(在weblogic.jar)實現了ServletContext接口。

在WebAppServletContext類有如下代碼:

public void removeAttribute(String s)

{

        Object obj = attributes.remove(s);

        eventsManager.notifyContextAttributeChange(s, null, obj);

 }

 

上面eventsManager是EventsManager類型的對象。

notifyContextAttributeChange方法的代碼:

void notifyContextAttributeChange(String s, Object obj, Object obj1)

{

        obj1 = unwrapAttribute(obj1);

        Iterator iterator = ctxAttrListeners.iterator();

        do

        {

            if(!iterator.hasNext())

                break;

            ServletContextAttributeListener servletcontextattributelistener= (ServletContextAttributeListener)iterator.next();

            if(obj1 == null)

            {

                if(obj != null)

                    servletcontextattributelistener.attributeAdded(new ServletContextAttributeEvent(context, s, obj));

            } else

            if(obj == null)

            {

                servletcontextattributelistener.attributeRemoved(new ServletContextAttributeEvent(context, s, obj1));

            } else

            {

                if(obj1.equals(obj))

                    return;

                servletcontextattributelistener.attributeReplaced(new ServletContextAttributeEvent(context, s, obj1));

            }

        } while(true);

 }

這裏是迭代一個保存了上下文屬性監聽器的叫ctxAttrListenersList(ctxAttrListeners是在系統啓動時從web.xml配置文件讀取上下文屬性監聽器配置實例化後存入的,然後根據參數值調用監聽器的相應的方法。

發佈了28 篇原創文章 · 獲贊 2 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章