`
574965385
  • 浏览: 7732 次
  • 性别: Icon_minigender_1
  • 来自: 西安
最近访客 更多访客>>
社区版块
存档分类
最新评论

记录用户在线时长

    博客分类:
  • java
 
阅读更多
    有些用户要求记录用户在线时长,刚做过这个功能,拿出来跟大家共享。
写SessionListener类做处理方法,该类需要继承HttpSessionBindingListener接口来侦听用户登录还是退出,或者是session失效。
private SysUser user;//系统用户

public SessionListener(SysUser user)
{
this.user = user;
}

//用户登录,信息记录在在线用户列表onlineUserLis中
public void valueBound(HttpSessionBindingEvent event)
{
HttpSession session = event.getSession();
ServletContext application = session.getServletContext();
List onlineUserList = (List)application.getAttribute("onlineUserList");
if (onlineUserList == null)
{
onlineUserList = new ArrayList();
application.setAttribute("onlineUserList", onlineUserList);
}
onlineUserList.add(user);
System.out.println((new StringBuilder(String.valueOf(user.getUserName()))).append("登录。").toString());
}

用户退出时记录时间并写入数据库
public void valueUnbound(HttpSessionBindingEvent event)
{
HttpSession session = event.getSession();
ServletContext application = session.getServletContext();
try
{
float onlineTime = 0.0F;
SimpleDateFormat df = new SimpleDateFormat("yyyy-M-d HH:mm:ss");

Date begin =df.parse(user.getLoginTime());

Date end = new Date();

long between = (end.getTime() - begin.getTime()) / 1000L;

long day1 = between / 0x15180L;

long hour1 = (between % 0x15180L) / 3600L;

long minute1 = (between % 3600L) / 60L;

onlineTime = (float)(day1 * 24L + hour1) + (float)minute1 / 60F;

SysRzList rzl = new SysRzList();
System.out.println(String.format("%10.1f",onlineTime));
//记录入库,最小单位0.1小时,也就是6分钟,一般是足够了。

}
catch(Exception ex){
ex.printStackTrace();
}
//将在线用户表中删除该用户
List onlineUserList = (List)application.getAttribute("onlineUserList");
onlineUserList.remove(user);

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics