essionListener访问JSF应用程序范围的托管bean

essionListener访问JSF应用程序范围的托管bean

本文介绍了如何从HttpSessionListener访问JSF应用程序范围的托管bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am running a JSF application and have declared some application-scoped backing beans (either in common-beans.xml or using the @ManagedBean and @ApplicationScoped annotations).

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

How can I access these beans from inside a javax.servlet.http.HttpSessionListener ?

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

I understand that the FacesContext is not available in the session listener so using:

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

...按预期投掷了NPE.

... threw a NPE as expected.

更新:

(在BalusC回答之前)

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

What I ended up doing was declare the application-wide information I needed to access in web.xml using env-entry elements (instead of using application-scoped beans) and then retrieve that information using:

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

这不是我的初衷,但这是一种解决方法.

It's not what I had in mind but it's a workaround.

推荐答案

JSF将应用程序范围的托管bean作为 ServletContext .

JSF stores application scoped managed beans as attributes of the ServletContext.

所以,这应该做:

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

另请参见:

08-06 09:18