日期:2014-05-18  浏览次数:20742 次

统计在线人数
如果没有登陆页码,
 只有一个JSP, 
用户访问它时, 

怎么统计用户的在线人数呢?

------解决方案--------------------
1 根据IP
2 根据Session

记录他们的最后访问时间,超过限定的时间的(比如5分钟)则视同离线
------解决方案--------------------
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
  
public class OnlineCounter extends HttpServlet implements HttpSessionListener,
HttpSessionAttributeListener,HttpSessionBindingListener {
public OnlineCounter(){
System.out.println("OnlineCounter initialized.");
}
private static final long serialVersionUID = 1L;
  
private static int sessionCounter = 0;
  
private static int attributeCounter = 0;
  
public void sessionCreated(HttpSessionEvent se) {
sessionCounter++;
System.out.println("session created");
}
  
public void sessionDestroyed(HttpSessionEvent se) {
sessionCounter--;
System.out.println("session destroied");
}
  
public void attributeAdded(HttpSessionBindingEvent se) {
attributeCounter++;
System.out.println("attribute added");
}
  
public void attributeRemoved(HttpSessionBindingEvent se) {
attributeCounter--;
System.out.println("attribute removed");
}
  
public void attributeReplaced(HttpSessionBindingEvent se) {
System.out.println(se.getName()+" replaced");
}

public void valueBound(HttpSessionBindingEvent event){
System.out.println(event.getName()+"_Bound_"+event.getValue());
}
  
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println(event.getName()+"_Unbound_"+event.getValue());
}
  
public static int getOnlineSession() {
return sessionCounter;
}
public static int getOnlineAttribute() {
return attributeCounter;
}
}

//---web.xml---
<listener>
<listener-class>包.OnlineCounter</listener-class>
</listener>


//------jsp页-----------
<%@ page contentType="text/html; charset=utf-8"%>
<%@ page import="SMART.JRSOFT.ONLINE.OnlineCounter"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html> 
<body>
<table>
<tr>
<td align="center" height="35">
当前在线人数: <%=OnlineCounter.getOnlineSession()%> 人
</td>
</tr>
</table>
</body>
</html>

------解决方案--------------------
探讨
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class OnlineCounter extends HttpServlet implements HttpSessionLis…