Javaweb實現線上人數統計程式碼例項
阿新 • • 發佈:2020-01-07
這篇文章主要介紹了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%>" rel="external nofollow" > <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" rel="external nofollow" > --> </head> <body> 線上人數為:<%=SessionCounter.getActiveSessions() %> </body> </html>
不用jsp頁面 寫成介面程式碼如下:
package com.wangyun.web.controllers; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class SessionCounter implements HttpSessionListener { 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; } } /** * 線上使用者人數 * @throws IOException * @throws ServletException */ @RequestMapping(value="user_online",method=RequestMethod.POST,produces="text/json;charset=utf-8") @ResponseBody public Object user_online() throws ServletException,IOException { JSONObject data = new JSONObject(); int number=SessionCounter.activeSessions; data.put("msg",number); return data.toString(); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。