javaweb中實現在線人數統計


session並不是瀏覽器關閉時銷毀的,而是在session失效的時候銷毀下列代碼就是監測session創建、銷毀

package com.my.count;

import javax.servlet.http.*;

public class SessionCounter implements HttpSessionListener {

    private static int activeSessions = 0;
    //session創建時執行
    public void sessionCreated(HttpSessionEvent se) {
        activeSessions++;
    }
    //session銷毀時執行
    public void sessionDestroyed(HttpSessionEvent se) {
        if (activeSessions > 0)
            activeSessions--;
    }
    //獲取活動的session個數(在線人數)
    public static int getActiveSessions() {
        return activeSessions;
    }

}

接下來就是配置web.xml

<listener>
      <listener-class>
          com.my.count.SessionCounter  //這里是包名加類名
      </listener-class>
  </listener>

接下來就可以在jsp頁面中使用

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="com.my.count.SessionCounter"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'ApplicationTest.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
        在線人數為:<%=SessionCounter.getActiveSessions() %>
  </body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM