簡単なHttpSessionListenerの例–アクティブセッションカウンター
Webアプリケーションでアクティブなセッションの総数を追跡するための簡単な「HttpSessionListener」の例を次に示します。 セッションの作成と削除の動作を引き続き監視する場合は、このリスナーを検討してください。
Javaソース
package com.example; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class SessionCounterListener implements HttpSessionListener { private static int totalActiveSessions; public static int getTotalActiveSession(){ return totalActiveSessions; } @Override public void sessionCreated(HttpSessionEvent arg0) { totalActiveSessions++; System.out.println("sessionCreated - add one session into counter"); } @Override public void sessionDestroyed(HttpSessionEvent arg0) { totalActiveSessions--; System.out.println("sessionDestroyed - deduct one session from counter"); } }
web.xml
com.example.SessionCounterListener
それがどのように働きますか?
–新しいセッションが作成された場合(例:「request.getSession();」 、リスナーのsessionCreated()が実行されます。
–セッションが破棄された場合(セッションのタイムアウトや「session.invalidate()」など)、リスナーのsessionDestroyed()が実行されます。
HttpSession session = request.getSession(); //sessionCreated() is executed session.setAttribute("url", "example.com"); session.invalidate(); //sessionDestroyed() is executed