単純なHttpSessionAttributeListenerの例

簡単なHttpSessionAttributeListenerの例

次に、Webアプリケーションでセッションの属性を追跡するための簡単な「HttpSessionAttributeListener」の例を示します。 セッションの属性の追加、更新、削除の動作を監視し続ける場合は、このリスナーを検討してください。

Javaソース

package com.example;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class MyAttributeListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        String attributeName = event.getName();
        Object attributeValue = event.getValue();
        System.out.println("Attribute added : " + attributeName + " : " + attributeValue);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        String attributeName = event.getName();
        Object attributeValue = event.getValue();
        System.out.println("Attribute removed : " + attributeName + " : " + attributeValue);
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        String attributeName = event.getName();
        Object attributeValue = event.getValue();
        System.out.println("Attribute replaced : " + attributeName + " : " + attributeValue);
    }
}

web.xml


        
        com.example.MyAttributeListener
    

それがどのように働きますか?

–新しいセッションの属性が追加されると、リスナーのattributeAdded()が実行されます。
–新しいセッションの属性が更新されると、リスナーのattributeReplaced()が実行されます。
–新しい場合セッションの属性が削除されると、リスナーのattributeRemoved()が実行されます。

  HttpSession session = request.getSession();
  session.setAttribute("url", "example.com"); //attributeAdded() is executed
  session.setAttribute("url", "example2.com"); //attributeReplaced() is executed
  session.removeAttribute("url"); //attributeRemoved() is executed

すべてのメソッドは引数として「HttpSessionBindingEvent」を受け入れるため、このイベントをトリガーした属性の名前と値を取得できます。