编写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方法: