这是一个简单的“ HttpSessionListener”示例,用于跟踪Web应用程序中活动会话的总数。 如果要继续监视会话的创建和删除行为,请考虑使用此侦听器。
Java源码
package com.mkyong;
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
<web-app ...>
<listener>
<listener-class>com.mkyong.SessionCounterListener</listener-class>
</listener>
</web-app>
它是如何工作的?
–如果创建了新会话,例如“ request.getSession();” ,将执行侦听器的sessionCreated()。
–如果会话被破坏,例如会话超时或“ session.invalidate()”,则将执行侦听器的sessionDestroyed()。
HttpSession session = request.getSession(); //sessionCreated() is executed
session.setAttribute("url", "mkyong.com");
session.invalidate(); //sessionDestroyed() is executed
标签: servlet
翻译自: https://mkyong.com/servlet/a-simple-httpsessionlistener-example-active-sessions-counter/