HttpSessionBindingListener和HttpSessionAttributeListener區別

來源:互聯網
上載者:User

標籤:區別   總結   src   pen   setattr   ini   body   ttext   attr   

 

  HttpSessionBindingListener和HttpSessionAttributeListener是兩個經常讓初學者弄混的監聽器,其實它們有很大的區別。這2個監聽器在文章中簡稱為BindingListener和AttributeListener.

    1.BindingListener有2個方法,valueBound(HttpSessinBindingEvent)和valueUnbount(HttpSessionBindingEvent)。實現BindingListener介面的對象被綁定到session時觸發valueBound事件,解除綁定時觸發valueUnbound事件。舉例來說:

 1 public class UserObject implements HttpSessionBindingListener 2 { 3     public void valueBound(HttpSessionBindingEvent event) 4     { 5         System.out.println("觸發綁定事件!"); 6     } 7     public void valueUnbound(HttpSessionBindingEvent event) 8     { 9         System.out.println("解除和session的綁定");10     }11 12 }
BindingListener

UserObject user = new UserObject();

當把該監聽器儲存到session中,session.setAttribute("user",user)時就會觸發valueBound事件.

當該監聽器從session中移除時即session.removeAttribute("user"),觸發valueUnbound事件;session失效或逾時

時也會觸發valueUnbound事件。

注意:只有當該監聽器(UserObject)儲存到session中或從session移除時才會觸發事件,其他沒有實現該listener對象儲存到session時不會觸發該事件。

    2.AttributeListener介面有3個方法,attributeAdded(HttpSessionBindingEvent),attributeRemoved(HttpSessionBindingEvent),

attributeReplaced(HttpSeesionEvent)。當在session中添加、移除或更改屬性值時會觸發相應的事件。例子:

 1 MyListener implements HttpSessionAttributeListener 2 { 3     attributeAdded(HttpSessionBindingEvenet event) 4     { 5          System.out.println("有對象加入session中"); 6     } 7      attributeRemoved(HttpSessionBindingEvent event) 8      { 9           System.out.println("有對象從session中移除");10      }11      attributeReplaced(HttpSessionBindingEvent event)12      {13           System.out.println("屬性值改變");14       }15 }
AttributeListener

OtherObject other = new OtherObject();

當有對象添加到session中時,session.setAttribute("object",other)觸發attributeAdded事件,

當該對象從session移除時,session.removeAttribute("object")觸發attriubteRemoved事件,

當該屬性的值發生變化時,  session.replaceAttribute("object",another)觸發attributeRepalced事件。

注意:只要有對象儲存到session中或從session中移除或改變屬性的值都會觸發相應事件,不論該對象是否實現了AttributeListener。

 

總結:1.只有實現了HttpSessionBindingListener的類,在和session綁定、解除綁定時觸發其事件。

        2.實現了HttpSessionAttributeListener後,任何對象(不論其是否實現了AttributeListener)在變化時均觸發對應的事件。

HttpSessionBindingListener和HttpSessionAttributeListener區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.