c# 统计当前在线人数_如何处理对非法关闭浏览器 ajax,计算系统当前在线人数(解决浏览器关闭不调用sessionDestroyed方法)...

编写SessionCounter类实现HttpSessionListener接口:

public class SessionCounter implements HttpSessionListener {

private static int activeSessions = 0;

public void sessionCreated(HttpSessionEvent se)

{ activeSessions++; } public void sessionDestroyed(HttpSessionEvent se)

{ if(activeSessions >

0) activeSessions--; } public static int getActiveSessions() { return activeSessions; } }

然后在web.xml添加一个监听器:

SessionCount.SessionCounter

我们可以通过getActiveSessions方法获取当前在线人数,但是,如果用户关闭浏览器的话,我们的在线人数是不会马上变的,即不会马上调用sessionDestroyed方法,只有等到session过期才会调用。

那么,怎样解决关闭浏览器的问题呢?

首先sessionDestroyed方法在以下两种情况下会调用:

1.session过期。

2.调用session.invalidate()方法。

那么我们编写一个Servlet用于session的invalidate:

public class CloseSessionServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public

CloseSessionServlet() {

super();

// TODO Auto-generated constructor stub

}

protected void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException

{

// TODO Auto-generated method

stub

request.getSession().invalidate();

}

protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException

{

// TODO Auto-generated method

stub

request.getSession().invalidate();

}

}

当我们关闭浏览器的时候,使用JavaScript捕获关闭浏览器的事件(onbeforeunload事件),然后发请求调用服务端的session的invalidate方法:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
using System; using System.Data; using System.Text; namespace ZKXP.BLL { /// /// OnLine 的摘要说明。 /// public class OnLine { private string USERNAME; private int OFFLINEDIFF; private int REMOVEDIFF; public OnLine() { //直接在这里设定、或从配置文件中读取配置参数 ///存放用户名的Session名 USERNAME = "UserName"; ///多少分钟不活动的用户在线列表中删除 OFFLINEDIFF = 5; ///多少秒执行一次删除不活动用户 REMOVEDIFF = 30; if(System.Web.HttpContext.Current.Application["OnlineTalbe"] == null) { this.CashTableInit(); } } public void CheckOnline() { //从Application获取数据表、获取SessionID DataTable dtOnline; dtOnline = (DataTable)System.Web.HttpContext.Current.Application["OnlineTalbe"]; string sessionId = System.Web.HttpContext.Current.Session.SessionID.ToString(); //数据表中是否有我的记录 DataRow drFind = dtOnline.Rows.Find(sessionId); if(drFind != null) { //有;更新我的状态 Info.Write("更新"); drFind["LastActiveTime"] = DateTime.Now; drFind["UserWhere"] = this.AtWhere; //用户由访客状态变为了登陆会员、或反之 if(Extend.GetSession(USERNAME) != null) { drFind["VisitorName"] = Extend.GetSession(USERNAME); drFind["VisitorLevel"] = Extend.GetSession("UserLevel"); } else { drFind["VisitorName"] = "vst"; drFind["VisitorLevel"] = -1; } } else { //无;加入关于我的在线信息 Info.Write("插入"); DataRow drNew = dtOnline.NewRow(); drNew["SessionID"] = sessionId; drNew["Visit
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值