这期内容当中小编将会给大家带来有关怎么在Javaweb中统计在线人数,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
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();
}
上述就是小编为大家分享的怎么在Javaweb中统计在线人数了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。