JAVA SERVLET api 在这个问题上为我们提供了 sessionCreated(HttpSessionEvent se) 和 sessionDestroyed(HttpSessionEvent se)。这些方法将分别被调用作为一个新会话被创建和会话即将被销毁的通知。让我们有如下的servlet代码
03.import javax.servlet.http.HttpSessionEvent;
04.import javax.servlet.http.HttpSessionListener;
05.import javax.servlet.http.HttpSession;
06.import java.util.List;
07.import java.util.ArrayList;
08.
09.public class SessionCounter implements HttpSessionListener
10.{
11. private List sessions = new ArrayList();
12.
13. public SessionCounter()
14. {
15. }
16.
17. public void sessionCreated(HttpSessionEvent event)
18. {
19. HttpSession session = event.getSession();
20. sessions.add(session.getId());
21.
22. session.setAttribute("counter", this);
23. }
24.
25. public void sessionDestroyed(HttpSessionEvent event)
26. {
27. HttpSession session = event.getSession();
28. sessions.remove(session.getId());
29.
30. session.setAttribute("counter", this);
31. }
32.
33. public int getActiveSessionNumber()
34. {
35. return sessions.size();
36. }
37.}
要显示用户数,我们将有一个 JSP 页面,如下所示
<html>
<head>
<title>Session Counter</title>
</head>
<body>
<%
SessionCounter counter = (SessionCounter) session
.getAttribute("counter");
%>
Number of online user(s): <%= counter.getActiveSessionNumber() %>
</body>
</html>
并设置 web.xml 文件我希望它有效