Servlet HttpSessionEvent統計線上使用者數範例


對談物件更改時通知HttpSessionEvent,此事件的相應偵聽器介面是HttpSessionListener

我們可以在這個事件上執行一些操作,例如:計數統計當前登入的使用者,記錄登入時間,登出時間等使用者詳細資訊。

HttpSessionListener介面的方法

HttpSessionListener介面中宣告了兩種方法,這些方法必須由servlet程式員來實現,以執行某些操作。

  • public void sessionCreated(HttpSessionEvent e):在建立對談物件時被呼叫。
  • public void sessionDestroyed(ServletContextEvent e):當對談無效時被呼叫。

HttpSessionEvent和HttpSessionListener統計當前登入使用者數的範例

在這個例子中,實現對當前登入的使用者進行統計。主要建立了以下幾個程式碼檔案:

  • index.html:從使用者處獲取輸入。
  • MyListener.java:一個偵聽器類,用於計算當前登入的使用者數量,並將此資訊作為屬性儲存在ServletContext物件中。
  • First.java:一個建立對談並列印登入使用者數量的Servlet類。
  • Logout.java:一個使對談無效的Servlet類。

開啟Eclipse,建立一個動態Web專案:HttpSessionEvent,其完整的目錄結構如下所示 -

以下是這個專案中的幾個主要的程式碼檔案。

檔案:index.html -

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>統計線上使用者數量</title>
</head>
<body>
    <div style="font-align: center;">
        <form action="first" method="post">
            使用者名:<input type="text" name="username" value="admin">密碼:<input
                type="password" name="password"><input
                type="submit" value="登入" />
        </form>
    </div>
</body>
</html>

監聽器檔案:CountUserListener.java -

package com.yiibai;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class CountUserListener implements HttpSessionListener {
    ServletContext ctx = null;
    static int total = 0, current = 0;

    public void sessionCreated(HttpSessionEvent e) {
        total++;
        current++;

        ctx = e.getSession().getServletContext();
        ctx.setAttribute("totalusers", total);
        ctx.setAttribute("currentusers", current);

    }

    public void sessionDestroyed(HttpSessionEvent e) {
        current--;
        ctx.setAttribute("currentusers", current);
    }

}

檔案:First.java -

package com.yiibai;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class FirstServlet extends HttpServlet {
    // 顯示使用者數
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        // retrieving data from ServletContext object
        ServletContext ctx = getServletContext();
        int t = (Integer) ctx.getAttribute("totalusers");
        int c = (Integer) ctx.getAttribute("currentusers");
        out.print("<br>使用者總數: " + t);
        out.print("<br>當前使用者數: " + c);
        out.print("<br><a href='logout'>登出</a>");
        out.close();
    }

    // 執行使用者登入
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String n = request.getParameter("username");
        String password = request.getParameter("password");
        // 假設輸入密碼為:123456時,此使用者登入成功
        if (password == null) {
            password = "";
        }
        if (password.equals("123456")) {
            out.print("您好, " + n);
            HttpSession session = request.getSession();
            session.setAttribute("uname", n);
        } else {
            out.print("登陸失敗 ~");
        }
        // retrieving data from ServletContext object
        ServletContext ctx = getServletContext();
        int t = (Integer) ctx.getAttribute("totalusers");
        int c = (Integer) ctx.getAttribute("currentusers");
        out.print("<br>使用者總數: " + t);
        out.print("<br>當前使用者數: " + c);
        out.print("<br><a href='logout'>登出</a>");
        out.close();
    }

}

檔案:LogoutServlet.java -

package com.yiibai;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LogoutServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession(false);
        session.invalidate();// invalidating session

        out.print("You are successfully logged out");

        out.close();
    }

}

檔案:web.xml -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>HttpSessionEvent</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
        <listener>
        <listener-class>com.yiibai.CountUserListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>FirstServlet</servlet-name>
        <servlet-class>com.yiibai.FirstServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FirstServlet</servlet-name>
        <url-pattern>/first</url-pattern>
    </servlet-mapping>    
    <servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>com.yiibai.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/logout</url-pattern>
    </servlet-mapping>
</web-app>

在編寫上面程式碼後,部署此Web應用程式(在專案名稱上點選右鍵->」Run On Server…」),開啟瀏覽器存取URL: http://localhost:8080/HttpSessionEvent/ ,如果沒有錯誤,應該會看到以下結果 -

開啟另一個瀏覽器存取URL: http://localhost:8080/HttpSessionEvent/ ,登入應用,然後登出,再次存取: http://localhost:8080/HttpSessionEvent/first ,應該看到以下結果 -