使用HttpSessionListener接口监听Session的创建和失效

在网站中经常需要进行在线人数的统计。过去的一般做法是结合登录和退出功能,即当用户输入用户名密码进行登录的时候计数器加1,然后当用户点击退出按钮退出系统的时候计数器减1。这种处理方式存在一些缺点,例如:用户正常登录后,可能会忘记点击退出按钮,而直接关闭浏览器,导致计数器减1的操作没有及时执行;网站上还经常有一些内容是不需要登录就可以访问的,在这种情况下也无法使用上面的方法进行在线人数统计。

import javax.servlet.http.HttpSessionListener;  
import javax.servlet.http.HttpSessionEvent;  
  
public class SessionCounter implements HttpSessionListener {  
private static int activeSessions =0;  
/* Session创建事件 */  
public void sessionCreated(HttpSessionEvent se) {  
      ServletContext ctx = event.getSession( ).getServletContext( );  
        Integer numSessions = (Integer) ctx.getAttribute("numSessions");  
        if (numSessions == null) {  
            numSessions = new Integer(1);  
        }  
        else {  
            int count = numSessions.intValue( );  
            numSessions = new Integer(count + 1);  
        }  
        ctx.setAttribute("numSessions", numSessions);  
}  
/* Session失效事件 */  
public void sessionDestroyed(HttpSessionEvent se) {  
 ServletContext ctx=se.getSession().getServletContext();  
 Integer numSessions = (Integer)ctx.getAttribute("numSessions");  
<span class="oblog_text">        if(numSessions == null)  
            numSessions = new Integer(0);  
        }  
        else {  
            int count = numSessions.intValue( );  
            numSessions = new Integer(count - 1);  
        }  
        ctx.setAttribute("numSessions", numSessions);</span>  
  
  
  
}  
}  
import javax.servlet.http.HttpSessionListener;  
import javax.servlet.http.HttpSessionEvent;  
  
public class SessionCounter implements HttpSessionListener {  
private static int activeSessions =0;  
/* Session创建事件 */  
public void sessionCreated(HttpSessionEvent se) {  
      ServletContext ctx = event.getSession( ).getServletContext( );  
        Integer numSessions = (Integer) ctx.getAttribute("numSessions");  
        if (numSessions == null) {  
            numSessions = new Integer(1);  
        }  
        else {  
            int count = numSessions.intValue( );  
            numSessions = new Integer(count + 1);  
        }  
        ctx.setAttribute("numSessions", numSessions);  
}  
/* Session失效事件 */  
public void sessionDestroyed(HttpSessionEvent se) {  
 ServletContext ctx=se.getSession().getServletContext();  
 Integer numSessions = (Integer)ctx.getAttribute("numSessions");  
<span class="oblog_text">        if(numSessions == null)  
            numSessions = new Integer(0);  
        }  
        else {  
            int count = numSessions.intValue( );  
            numSessions = new Integer(count - 1);  
        }  
        ctx.setAttribute("numSessions", numSessions);</span>  
  
  
  
}  
}  
<listener>  
    <listener-class>test.listener.SessionCounter</listener-class>  
</listener> 

<session-config>  
    <session-timeout>1</session-timeout>  
</session-config>

参考地址:http://uule.iteye.com/blog/824115

posted on 2016-09-12 10:31  james-roger  阅读(2895)  评论(0编辑  收藏  举报