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/ ,如果沒有錯誤,應該會看到以下結果 -

Servlet

打開另一個瀏覽器訪問URL: http://localhost:8080/HttpSessionEvent/ ,登錄應用,然後註銷,再次訪問: http://localhost:8080/HttpSessionEvent/first ,應該看到以下結果 -

Servlet