Search code examples
jsf-2myfaces

What happens to @SessionScoped @ManagedBean which is already in HttpSession?


Old code creates a @SessionScoped @ManagedBean (namely UserSession) at the first request in a ServletFilter and puts it in the HttpSession (if not already there).

Now what happens when some EL expression tries to access that ManagedBean the first time? I expected a second instance of UserSession (one created manually and one from JSF). So I instrumented the constructor, @PostConstruct and @PreDestroy with a few logging statements. Now it seems JSF never creates the UserSession - only the constructor is called.

Is this possible? Can JSF reuse that bean from HttpSession? Is it legit to put @SessionScoped beans in HttpSession?


Solution

  • Your observation is correct. Under JSF's covers, JSF itself also stores session scoped managed beans as an attribute of the HttpSession. So if it's already present, it will just be reused, regardless of the way how it has ended up in there.

    Whether that's good or bad depends on the concrete functional requirement. Given your astonishment, I'd guess that it's bad and that you need to revise either the approach or the functional requirement. Perhaps you need a secondary (session scoped?) managed bean which injects the particular session attribute by @ManagedProperty.