通過實(shí)現(xiàn)session監(jiān)聽器,將退出的用戶從列表中刪除
在web.xml進(jìn)行如下配置
<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);
}
}
}