记录用户在线时长

有些用户要求记录用户在线时长,刚做过这个功能,拿出来跟大家共享。
写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);

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值