5

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).

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

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")
       ...
    }

... threw a NPE as expected.

UPDATE:

(before BalusC answer)

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.

Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331

1 Answers1

9

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

So, this should do:

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

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555