如何从HttpSessionListener访问JSF应用程序范围的管理bean?

5
我正在运行一个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");

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

1个回答

9

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

因此,这样做即可:

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

参见:


注意:以上链接提供了关于如何在JavaServer Faces(JSF)中访问和修改托管Bean的有用信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接