记录用户在线时长

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

}

你可能感兴趣的:(用户)