Question

Continuing on my previous question, I'm trying to initialize a session-scoped JSF bean when the application's session first starts, so the bean will be available to a user, regardless of which page they access on my web application first. My custom listener:

public class MyHttpSessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
                .get("mySessionBean") == null) {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
                    .put("mySessionBean", new MySessionBean());
        }
    }
}

However, this is giving me a stack overflow error. It appears that the put() method in the SessionMap class tries to create a new HttpSession, thus causing an infinite loop to occur with my listener. How can I initialize a JSF session-scoped bean when my application's session first starts, without running into this issue?

I'm using JSF 2 with Spring 3, running on WebSphere 7.

Thanks!

Was it helpful?

Solution

The session isn't been fully finished creating at that point. Only when the listener method leaves, the session is put into the context and available by request.getSession() as JSF's getSessionMap() is using under the covers.

Instead, you should be grabbing the session from the event argument and use its setAttribute() method. JSF lookups and stores session scoped managed beans just there and won't create a new one if already present.

public void sessionCreated(HttpSessionEvent event) {
    event.getSession().setAttribute("mySessionBean", new MySessionBean());
}

Note that I removed the superfluous nullcheck as it's at that point impossible that the session bean is already there.


Unrelated to the concrete problem, you should actually never rely on the FacesContext being present in an implementation which isn't managed by JSF. It is quite possible that the session can be created during a non-JSF request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top