web.xml中加入:
<!--=====================监听器========================-->
<listener>
<listener-class>cn.com.mycm.common.listener.OnlineUserList</listener-class>
</listener>
然后编写类:
package cn.com.mycm.common.listener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import cn.com.headsoft.common.dao.UserDAO;
import cn.com.headsoft.common.dao.DAOFactory;
import java.util.Set;
import java.util.LinkedHashSet;
/**
* 公共模块--监听器--在线用户列表类
*/
public class OnlineUserList implements HttpSessionListener, HttpSessionAttributeListener
{
/**
* 在线用户列表,static保证整个系统只有一个在线用户列表,Set保证元素不重复
*/
private static Set list = new LinkedHashSet();
/**
* Session创建:此处并未往数据库增加记录,增加记录是在用户登录类中处理的
*/
public void sessionCreated(HttpSessionEvent se)
{
}
/**
* Session激活
*/
public void sessionDidActivate(HttpSessionEvent se)
{
}
/**
* Session将要过期
*/
public void sessionWillPassivate(HttpSessionEvent se)
{
}
/**
* Session销毁:更新数据库日子表中的退出系统时间
*/
public void sessionDestroyed(HttpSessionEvent se)
{
HttpSession session = se.getSession();
DAOFactory factory = new DAOFactory();
UserDAO dao = factory.getUserDAO();
dao.updateLogoutTimeBySessionId(session.getId());
session.invalidate();
}
/**
* Session属性增加:往在线用户列表里增加用户
*/
public void attributeAdded(HttpSessionBindingEvent se)
{
if (se.getName().equals("userid"))
{
list.add(se.getValue());
}
}
/**
* Session属性移除:往在线用户列表里移除用户
*/
public void attributeRemoved(HttpSessionBindingEvent se)
{
if (se.getName().equals("userid"))
{
list.remove(se.getValue());
}
}
/**
* Session属性替换
*/
public void attributeReplaced(HttpSessionBindingEvent se)
{
}
/**
* 返回在线用户列表
*/
public static Set getOnLineUserList()
{
return list;
}
}