用Session监听器,试下吧。将Session存活时间设短点。。。
一、实现Session监听器
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnlineCounter implements HttpSessionListener {
public synchronized void sessionCreated(HttpSessionEvent se){
String count = (String)se.getSession().getServletContext().getAttribute("count");
int c=0;
if(count !=null){
c = Integer.valueOf(count).intValue();
System.out.println("旧Count:"+c);
se.getSession().getServletContext().setAttribute("count",(c+1)+"");
}else{
System.out.println("新Count");
se.getSession().getServletContext().setAttribute("count",c+1+"");
}
System.out.println("建立session时 Count:"+c);
}
public synchronized void sessionDestroyed(HttpSessionEvent se){
System.out.println("session失效时 ");
String count = (String)se.getSession().getServletContext().getAttribute("count");
int c=0 ;
if(count !=null){
c = Integer.valueOf(count).intValue();
if(c>=1){
System.out.println("sessionDestroyed:旧c-1:"+c);
se.getSession().getServletContext().setAttribute("count",(c-1)+"");
}
}else{
System.out.println("sessionDestroyed:旧新"+c);
se.getSession().getServletContext().setAttribute("count","1");
}
// session失效时
}
}
二、配置Session监听器 与Session存活时间
<listener>
<listener-class>
com.longqiao.tools.servlet.OnlineCounter
</listener-class>
</listener>
<session-config>
<session-timeout>1 </session-timeout> <!-- Session存活时间为1分钟 -->
</session-config>
三、从前台提出网站在线人数...
当前在线人数:${applicationScope.count}