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
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值