2010-05-04 97 views

回答

1

我不做春天,但在正常JSF/JSP/Servlet的,你會抓住HttpSessionBindingListener這一點。基本上,您需要給會話範圍bean一個static List<Bean>屬性並相應地實現該接口,以更新valueBound()valueUnbound()方法中的static列表。

您可以在this answer找到詳細的代碼示例。

0

這裏是我想出了一個解決方案利用彈簧:

我進行正常的春季單例的bean稱爲SessionBeanHolder。 這個bean擁有我的會話bean的列表。 當用戶登錄時,我將會話bean添加到我的SessionBeanHolder中。

在Spring中引用會話bean時,實際上是指代理。 因此,使這項工作的關鍵是獲取底層bean以添加到SessionBeanHolder中。

下面是示例代碼:

注:我的會話bean被稱爲SessionInfo。

@Scope(value="singleton") 
@Component 
public class SessionBeanHolder { 

    static Set<SessionInfo> beans; 

    public SessionBeanHolder() { 
     beans = new HashSet<SessionInfo>(); 
    } 

    public Collection<SessionInfo> getBeans() { 
     return beans; 
    } 

    public void addBean(SessionInfo bean) { 
     try { 
      this.beans.add(removeProxyFromBean(bean)); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    // Fetch the underlying bean that the proxy refers to 
    private SessionInfo removeProxyFromBean(SessionInfo proxiedBean) { 
     if (proxiedBean instanceof Advised) { 
      try { 
       return (SessionInfo) ((Advised) proxiedBean).getTargetSource().getTarget(); 
      } catch (Exception e) { 
       throw new RuntimeException(e); 
      } 
     } else { 
      return proxiedBean; 
     } 
    } 
} 

當然,只要你想添加的會話Bean或者獲取所有Bean的列表,只需在自動裝配和SessionBeanHolder使用它的方法。

@Autowired 
    SessionBeanHolder sessionBeanHolder;