您的位置:首页 > 其它

listner监听器 ___计算系统当前在线人数(解决浏览器关闭不调用sessionDestroyed方法)

2017-07-01 18:51 453 查看


计算系统当前在线人数(解决浏览器关闭不调用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添加一个监听器:
<listener> 

<listener-class>SessionCount.SessionCounter</listener-class> 

</listener>
我们可以通过getActiveSessions方法获取当前在线人数,但是,如果用户关闭浏览器的话,我们的在线人数是不会马上变的,即不会马上调用sessionDestroyed方法,只有等到session过期才会调用。
那么,怎样解决关闭浏览器的问题呢?
首先sessionDestroyed方法在以下两种情况下会调用:
1.session过期。
2.调用session.invalidate()方法。
那么我们编写一个Servlet用于session的invalidate:
public class CloseSessionServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public CloseSessionServlet() {

        super();

        // TODO Auto-generated constructor stub

    }
/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

   // TODO Auto-generated method stub

   request.getSession().invalidate();

}
/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

   // TODO Auto-generated method stub

   request.getSession().invalidate();

}
}
当我们关闭浏览器的时候,使用JavaScript捕获关闭浏览器的事件(onbeforeunload事件),然后发请求调用服务端的session的invalidate方法:
<% String clsoeSessionPath = "http://" + request.getServerName() + ":" + request.getServerPort() + "/test/CloseSession"; %>

<script type="text/javascript">

    window.onbeforeunload = function()   

    {   

        if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey)   

        {   

        window.location.href='<%=clsoeSessionPath%>';        

        }   

    }     

</script>
那么就解决了关闭浏览器,sessionDestroyed方法没有马上调用的问题。
http://blog.163.com/chengwei_1104/blog/static/53645274201341524826633/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐