How to access JSF application-scoped managed beans from an HttpSessionListener?
jsf
Solution
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:
- Get JSF managed bean by name in any Servlet related class
- Access and modify property(ies) of an Application-Scoped Managed Bean from Session Listener
Problem
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.