Servlet監聽器統計線上人數

文采杰出發表於2024-04-21
  • 首先,我們需要建立一個HttpSessionListener來監聽會話的建立和銷燬事件。當新的會話建立時,我們將增加線上人數;當會話銷燬時,我們將減少線上人數。
public class OnlineCounterListener implements HttpSessionListener {
    private static int activeSessions = 0;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
//        HttpSessionListener.super.sessionCreated(se);
        activeSessions++;
        System.out.println("Session created. Active sessions: " + activeSessions);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
//        HttpSessionListener.super.sessionDestroyed(se);
        if (activeSessions > 0) {
            activeSessions--;
            System.out.println("Session destroyed. Active sessions: " + activeSessions);
        }
    }
    public static int getActiveSessions(){
        return activeSessions;
    }
}
  • 接下來,我們需要在web.xml檔案中配置該監聽器,每當有新的使用者訪問應用程式時,都會建立一個新的會話,從而觸發sessionCreated方法,增加線上人數。當會話過期或使用者關閉瀏覽器時,會觸發sessionDestroyed方法,減少線上人數。
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <listener>
        <listener-class>com.example.OnlineCounterListener</listener-class>
    </listener>

    <!-- Servlet and JSP configurations would go here -->

</web-app>
  • 建立一個Servlet和JSP頁面來顯示線上人數:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/online-count")
public class OnlineCountServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int activeUsers = OnlineCounterListener.getActiveSessions();
        request.setAttribute("activeUsers", activeUsers);
        request.getRequestDispatcher("/online-count.jsp").forward(request, response);
    }
}
  • JSP示例 (在webapp資料夾下新建online-count.jsp):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Online User Count</title>
</head>
<%
    session.setMaxInactiveInterval(10);// 設定session有效時間
%>
<body>
    <h1>Currently Online: ${activeUsers}</h1>
</body>
</html>

啟動tomcat,瀏覽器訪問http://localhost:8080/自定義應用程式上下文/online-count,
輸出結果: Currently Online: 2

相關文章