实现在线人数统计

在很多web项目中会需要在线人数统计。
前端时间做了一个这样的模块,具体实现如下:
(1) web.xml
session超时定义是必须的:
<!-- session超时定义,单位为分钟 -->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
监听器:
<!-- 监听器 -->
<listener>         
<listener-class>com.coolhu.web.action.login.OnlineSessionListener</listener-class>     
</listener>
(2 )OnlineSessionListener监听器:
public class OnlineSessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
@SuppressWarnings("unchecked")
public void sessionDestroyed(HttpSessionEvent event) {

HttpSession session = event.getSession();
ServletContext application = session.getServletContext();
WebApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(application);
// 取得登录的用户名
UserPO userPO = (UserPO) session
.getAttribute("user");//从session中获得user信息
if (userPO != null) {
// 从在线列表中删除用户名
Vector<OnlineUsersPO> onlineUserV = (Vector<OnlineUsersPO>) application
.getAttribute("onlineUserV");
Iterator iter = onlineUserV.iterator();
OnlineUsersPO po = null;
while (iter.hasNext()) {
po = (OnlineUsersPO) iter.next();
if (po.getUserSessionId() != null
&& po.getUserSessionId().equals(session.getId())) {
break;
}
}
onlineUserV.remove(po);

}
}
(3)因为用的struts2,所以我的登录的action是这么写的:
public String login(){
ServletContext application = request.getSession()
.getServletContext();
Vector<OnlineUsersPO> onlineUserV = (Vector<OnlineUsersPO>) application
.getAttribute("onlineUserV");
// 第一次使用前,需要初始化
if (onlineUserV == null) {
onlineUserV = new Vector<OnlineUsersPO>();
application.setAttribute("onlineUserV", onlineUserV);
}
// 向集合中添加添加登录的相关信息
onlineUserV = addOnlineInfo(onlineUserV, user, loginName, request
.getSession().getId());
}
使用到的addOnlineInfo方法:
private Vector<OnlineUsersPO> addOnlineInfo(
Vector<OnlineUsersPO> onlineUserV, UserPO user, String loginName,
String sessionId) {
if (user != null) {
OnlineUsersPO po = new OnlineUsersPO();
po.setLoginName(loginName);//登录人
Timestamp time = new Timestamp(new Date().getTime());
po.setLoginTime(time);//登录时间
po.setUserId(po.getUserId());//用户id
po.setUserSessionId(sessionId);//sessionid
//ip
String ip = "";
ip = getIpAddr(request);
if(ip!=null)
po.setLoginIp(ip);//登录ip
onlineUserV.add(po);

}
return onlineUserV;
}
//getIpAddr是获取登录用户ip信息的
private String getIpAddr(HttpServletRequest request) {
       String ip = request.getHeader("x-forwarded-for");
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getHeader("Proxy-Client-IP");
       }
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getHeader("WL-Proxy-Client-IP");
       }
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getRemoteAddr();
       }
       return ip;
   }
。。。。。。后台的登录到注销一系列的统计完成了。
剩下就需要在页面显示了,将Vector<OnlineUsersPO> onlineUserV 集合读取出来,安排好显示即可!

你可能感兴趣的:(xml,Web)