我们可以用监听器实现在线人数的统计,步骤如下。
<br/>
**1. 实现接口HttpSessionListener**
```java
public class CustomSessionListener implements HttpSessionListener {
private Long count = 1L;
/**
* session被创建时调用
*/
@Override
public void sessionCreated(HttpSessionEvent arg0) {
System.out.println("sessionCreated");
count = count + 1;
arg0.getSession().setAttribute("count", count);
}
/**
* session被销毁时被调用
*/
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("sessionDestroyed");
count = count - 1;
se.getSession().setAttribute("count", count);
}
}
```
**2. `web.xml`中注册监听器**
```xml
<listener>
<listener-class>com.learn.servlet02.listener.CustomSessionListener</listener-class>
</listener>
```
**3. 编写一个Servlet用来演示**
```java
@WebServlet("/listener")
public class ListenerServlet extends BaseServlet {
public void listener04(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
System.out.println("在线人数 -> " + session.getAttribute("count"));
//在线人数 -> 3
}
}
```