第1步 准备session监听器处理类。
package com.ane56.common.util;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
/**
* Created by liyang on 2016/11/28.
*/
public class SessionListener implements HttpSessionAttributeListener {
/**
* 定义监听的session属性名.
*/
public final static String LISTENER_NAME = "_login";
/**
* 定义存储客户登录session的集合.
*/
private static List sessions = new ArrayList();
/**
* 加入session时的监听方法.
*
* @param sbe
* session事件
*/
public void attributeAdded(HttpSessionBindingEvent sbe) {
if (LISTENER_NAME.equals(sbe.getName())) {
sessions.add(sbe.getValue());
}
}
/**
* session失效时的监听方法.
*
* @param sbe
* session事件
*/
public void attributeRemoved(HttpSessionBindingEvent sbe) {
if (LISTENER_NAME.equals(sbe.getName())) {
sessions.remove(sbe.getValue());
}
}
/**
* session覆盖时的监听方法.
*
* @param sbe
* session事件
*/
public void attributeReplaced(HttpSessionBindingEvent sbe) {
}
/**
* 返回客户登录session的集合.
*
* @return
*/
public static List getSessions() {
return sessions;
}
}
中的_login就是设定的特殊session属性,当然你可以改成别的名字。
第2步 将session监听器配置到web.xml中.
com.common.util.SessionListener
第3步 当用户登录时监听用户。
//记入session监听器
session.setAttribute(com.stephen.filter.SessionListener.LISTENER_NAME,
new OnlineSession(request.getRemoteAddr(),userName,new Date().toString()));
注意在上面的代码中使用了新的OnlineSession类,OnlineSession类封装了登录用户的信息(如用户ip,用户名,登录时间等).
/**
* Created by liyang on 2016/11/28.
*/
public final class OnlineSession {
/**
* 客户计算机的ip.
*/
private String ip = null;
/**
* 客户登录名.
*/
private String loginId = null;
/**
* 客户登录系统时间.
*/
private String onlineTime = null;
private String timeCompare = null;
...
第4步 显示在线用户的情况。
String path = request.getContextPath();
String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";
%>
user managefunction date2str(x, y) {
var z = {
y: x.getFullYear(),
M: x.getMonth() + 1,
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
return y.replace(/(y+|M+|d+|h+|m+|s+)/g, function(v) {
return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-(v.length > 2 ? v.length : 2))
});
}
function fmt_time(value){
var unixTimestamp = new Date(value);
return date2str(unixTimestamp, "yyyy-MM-d h:m:s")
}
工号登录IP登录时间登录时长
第5步 在线用户登出,清除session记录。
@RequestMapping("logout")
public void logout(HttpSession session) {
//清楚session相关记录
session.removeAttribute(com.ane56.common.util.SessionListener.LISTENER_NAME);
}