通过实现session监听器,将退出的用户从列表中删除
在web.xml进行如下配置
<listener>
<listener-class>cn.com.Demo.Listener.MyListener</listener-class>>
</listener>>
然后代码如下
public class MyListener implements HttpSessionListener,
HttpSessionActivationListener {
@Override
public void sessionDidActivate(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void sessionWillPassivate(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Create session"+arg0.getSession().getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("destroyed session"+arg0.getSession().getId());
HttpSession session = arg0.getSession();
String userName = (String)session.getAttribute("LOGIN_USER");
ServletContext ctx = session.getServletContext();
Set<String> userSet = (Set<String>)ctx.getAttribute("USER_SET");
if(userSet!=null)
{
userSet.remove(userName);
}
}
}