package com.hjdf.szcgWeb.web.filter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import com.hjdf.szcgWeb.model.Users;
public class SessionListener implements HttpSessionListener {
private static Set<HttpSession> sessionCache = new HashSet<HttpSession>();
private static Object mutexLock = new Object();
public static SessionListener instance ;
public SessionListener(){
instance = this;
}
public void sessionCreated(HttpSessionEvent event) {
HttpSession session = event.getSession();
synchronized(mutexLock){
sessionCache.add(session);
System.out.println("Current user count:" + sessionCache.size());
}
}
public void sessionDestroyed(HttpSessionEvent event) {
synchronized(mutexLock){
sessionCache.remove(event.getSession());
}
}
public static void invalidateSessionIfNecessary(HttpSession currentUserSession, Users usr){
synchronized(mutexLock){
HttpSession userSession = null;
for(HttpSession session : sessionCache){
Users sessionUser = null;
try{
sessionUser = (Users) session.getAttribute("user");
}catch(IllegalStateException e){
continue;
}
if(sessionUser != null && sessionUser.getId() == (usr.getId())){
session.invalidate();
userSession = session;
break;
}
}
if(userSession != null){
sessionCache.remove(userSession);
}
currentUserSession.setAttribute("user", usr);
}
}
}