【问题标题】:How to access JSF application-scoped managed beans from an HttpSessionListener? [duplicate]如何从 HttpSessionListener 访问 JSF 应用程序范围的托管 bean? [复制]
【发布时间】:2012-11-17 09:19:27
【问题描述】:

我正在运行一个 JSF 应用程序并声明了一些应用程序范围的支持 bean(在 common-beans.xml 中或使用 @ManagedBean@ApplicationScoped注释)。

如何从 javax.servlet.http.HttpSessionListener 内部访问这些 bean?

我了解FacesContext 在会话侦听器中不可用,因此使用:

public class AnHTTPSessionListener implements HttpSessionListener {
    ...
    public void sessionDestroyed(HttpSessionEvent e) {
        AppBean appBean = (AppBean) FacesContext.getCurrentInstance()
                                                .getExternalContext()
                                                .getApplicationMap().get("appBean")
       ...
    }

...按预期抛出 NPE。

更新:

(在 BalusC 回答之前)

我最终做的是使用 env-entry 元素在 web.xml 中声明我需要访问的应用程序范围的信息(而不是使用应用程序范围的 bean ) 然后使用以下方法检索该信息:

   InitialContext ic = new InitialContext();
   Context env = (Context) ic.lookup("java:comp/env");
   appName = (String) env.lookup("appBeanValue");

这不是我的想法,但这是一种解决方法。

【问题讨论】:

    标签: jsf


    【解决方案1】:

    JSF 将应用程序范围的托管 bean 存储为 ServletContext 的属性。

    所以,应该这样做:

    public void sessionDestroyed(HttpSessionEvent e) {
        AppBean appBean = (AppBean) e.getSession().getServletContext().getAttribute("appBean");
        // ...
    }
    

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 2012-12-26
      • 2012-03-27
      • 2013-10-19
      • 2012-08-27
      • 1970-01-01
      • 2011-06-28
      相关资源
      最近更新 更多