我假设您的应用程序实际上是独立的上下文。我所做的事情与您在
HttpSessionListener每种情况下使用的要求类似。这里最棘手的部分是,您需要具有一个由根类加载器而不是上下文类加载器加载的Session
Collection。这是我记得的方式:
创建一个类,其中包含每个上下文的活动会话。此类 必须 位于tomcat / lib目录中,以便每个上下文均可访问。它不能是任何上下文的一部分。
public class SessionMap { private static Map<ServletContext, Set<HttpSession>> map = new HashMap<ServletContext, Set<HttpSession>>(); private SessionMap() { } public static Map<ServletContext, Set<HttpSession>> getInstance() { return map; } public static void invalidate(String[] contexts) { synchronized (map) { List<String> l = Arrays.asList(contexts);for (Map.Entry<ServletContext, Set<HttpSession>> e : map.entrySet()) { // context name without the leading slash String c = e.getKey().getContextPath().substring(1); if (l.contains(c)) { for (HttpSession s : e.getValue()) s.invalidate(); } } } }}为每个上下文创建一个侦听器。
public class ApplicationContextListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent event) { ConcurrentMap<ServletContext, Set<HttpSession>> instance = SessionMap.getInstance(); synchronized (instance) { ServletContext c = event.getSession().getServletContext(); Set<HttpSession> set = instance.get(c); if (c == null) { set = new HashSet<HttpSession>(); instance.put(c, set); } set.add(event.getSession()); } } public void sessionDestroyed(HttpSessionEvent event) { ConcurrentMap<ServletContext, Set<HttpSession>> instance = SessionMap.getInstance(); synchronized (map) { ServletContext c = event.getSession().getServletContext(); Set<HttpSession> set = instance.get(c); if (c != null) { set.remove(event.getSession()); } } }}在相应上下文的中注册每个侦听器
web.xml。
<listener> <listener-class>ApplicationContextListener</listener-class></listener>
然后,您可以调用以下行以使任何上下文中的所有内容均无效。
SessionMap.invalidate();
为了安全起见,我正在地图上进行同步。



