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.
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 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");
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With