Vaadin close UI of same user in another browser/tab/system

末鹿安然 提交于 2019-12-04 16:47:04

I have a situation similar to your where I need to display several info regarding all sessions. What I did was I created my own Servlet extending the VaadinServlet with a static ConcurrentHashmap to save my sessions info, and a SessionDestroyListener to remove any info from the map upon logout. Initially I also had a SessionInitListener where I added the info in the hashmap but I realized I only had the user information after authentication so I moved this part to the page handling the login.

I guess you could do something similar, or at least this should get you started:

public class SessionInfoServlet extends VaadinServlet {

  private static final ConcurrentHashMap<User, VaadinSession> userSessionInfo = new ConcurrentHashMap<>();

  // this could be called after login to save the session info
  public static void saveUserSessionInfo(User user, VaadinSession session) {
    VaadinSession oldSession = userSessionInfo.get(user);
    if(oldSession != null){
      // close the old session
      oldSession.close();
    }
    userSessionInfo.put(user, session);
  }

  public static Map<User, VaadinSession> getUserSessionInfos() {
    // access the cache if we need to, otherwise useless and removable
    return userSessionInfo;
  }

  @Override
  protected void servletInitialized() throws ServletException {
    super.servletInitialized();
    // register our session destroy listener
    SessionLifecycleListener sessionLifecycleListener = new SessionLifecycleListener();
    getService().addSessionDestroyListener(sessionLifecycleListener);
  }

  private class SessionLifecycleListener implements SessionDestroyListener {
    @Override
    public void sessionDestroy(SessionDestroyEvent event) {
      // remove saved session from cache, for the user that was stored in it
      userSessionInfo.remove(event.getSession().getAttribute("user"));
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!