HttpSessionEvent class gives notifications for changes to sessions within a web application. HttpSessionListener receives notifications of changes to the list of active sessions in a web application and perform some action. HttpSessionListener is used to perform some important tasks when a session is created or destroyed. For example: counting the number of active session.
HttpSessionEvent类提供有关Web应用程序中会话更改的通知。 HttpSessionListener接收Web应用程序中活动会话列表更改的通知,并执行一些操作。 创建或销毁会话时,HttpSessionListener用于执行一些重要的任务。 例如:计算活动会话数。
Servlet:与会话相关的其他一些侦听器 (Servlet: Some other Session related Listeners)
Listener | Description |
---|---|
HttpSessionActivationListener | Let's you know when a session moves from one Virtual machine to another. |
HttpSessionBindingListener | Le's your attribute class object get notified when they are added or removed from session. |
HttpSessionAttributeListener | Let's you know when any attribute is added, removed or replaced in a session. |
听众 | 描述 |
---|---|
HttpSessionActivationListener | 让我们知道会话何时从一台虚拟机转移到另一台虚拟机。 |
HttpSessionBindingListener | 当您将其添加到会话中或从会话中删除时,Le的属性类对象将得到通知。 |
HttpSessionAttributeListener | 让我们知道在会话中何时添加,删除或替换任何属性。 |
HttpSessionListener的方法 (Methods of HttpSessionListener)
Methods | Description |
---|---|
void sessionCreated(HttpSessionEvent e) | notification that a session was created. |
void sessionDestroyed(HttpSessioEvent e) | notification that a session was destroyed. |
方法 | 描述 |
---|---|
void sessionCreated(HttpSessionEvent e) | 通知已创建会话。 |
无效sessionDestroyed(HttpSessioEvent e) | 通知会话已被破坏。 |
HttpSessionListener的示例 (Example of HttpSessionListener)
In this example we will create a session listener that will count the number of active sessions in a web application.
在此示例中,我们将创建一个会话侦听器,该侦听器将计算Web应用程序中活动会话的数量。
MySessionCounter.java
MySessionCounter.java
import javax.servlet.http.*;
public class MySessionCounter implements HttpSessionListener {
private static int sessionCount;
public int getActiveSession()
{
return sessionCount;
}
public void sessionCreated(HttpSessionEvent e)
{
sessionCount++;
}
public void sessionDestroyed(HttpSessionEvent e)
{
sessionCount--;
}
}
web.xml
web.xml
<web-app ...>
<listener>
<listener-class>MySessionCounter</listener-class>
</listener>
</web-app>
翻译自: https://www.studytonight.com/servlet/httpsession-event-and-listener.php