页面跳转时才会退出,要主动退出,需要js的定时心跳包
//userid=httpsession public static Map<Integer, HttpSession> USERID_SESSIONS = new ConcurrentHashMap<Integer, HttpSession>();
public static void addLoginUser(HttpServletRequest request,Map<String, Object> user){ //退出之前的session int id = StringUtil.toInt(user.get("id")); if (id>0) { HttpSession session_old = ChipmunkCache.USERID_SESSIONS.get(id); if (session_old!=null) { ChipmunkCache.USERID_SESSIONS.remove(id); System.out.println("old sessionid:"+session_old.getId()); System.out.println(session_old.isNew()); session_old.removeAttribute(SESSION_USER); session_old.invalidate();//销毁session,会调用HttpSessionListener的sessionDestroyed } HttpSession session_new = request.getSession(); System.out.println("new sessionid:"+session_new.getId()); session_new.setAttribute(SESSION_USER, user); ChipmunkCache.USERID_SESSIONS.put(id, session_new); } //add(request, SESSION_USER, user); } public static void removeLoginUser(HttpServletRequest request){ HttpSession session = request.getSession(); Map<String, Object> user = getLoginUser(session); if (user!=null) { int id = StringUtil.toInt(user.get("id")); ChipmunkCache.USERID_SESSIONS.remove(id); } session.removeAttribute(SESSION_USER); //重置sessionid,防漏洞 try { session.invalidate(); } catch (Exception e) { e.printStackTrace(); } }
public class MySessionListener implements HttpSessionListener{ private static AtomicInteger online_count = new AtomicInteger(0); @Override public void sessionCreated(HttpSessionEvent event) { int count = online_count.incrementAndGet(); System.out.println("online count:"+count); HttpSession session = event.getSession(); // online_user_map.put(session.getId(), value) } @Override public void sessionDestroyed(HttpSessionEvent event) { HttpSession session = event.getSession(); int count = online_count.decrementAndGet(); System.out.println("online count:"+count); } }