Search code examples
jsfjakarta-eemojarra

How to limit the number of @ViewScoped beans


I'm using GF4. In my app I have a main menu which is always visible to the user. One of the menu items refers to a @ViewScoped backing bean, which is being created and its @PostConstruct method called every time the user clicks on this menu item, which is the expected behavior.

The problem arises when the user clicks on some other menu item, because the @ViewSoped bean continues to exist, i.e. its @PreDestroy method is not being called.

Looking for an answer I came across this stackoverflow post which proposes setting those two parameters: com.sun.faces.numberOfViewsInSession andcom.sun.faces.numberOfLogicalViews. Since I want only one @ViewScoped bean at a time I set them both in web.xml to 1. But this has no effect! Hence my questions:

  1. Is web.xml the right place?

  2. Is there a way to affect the container managed beans, i.e. manually destroy them?

    Thanks in advance!


Solution

  • I found the answer here JSF 2.2 Memory Consumption: Why does Mojarra keep the ViewScoped Beans of the last 25 Views in Memory?. The user there provides the solution in his question. So one have to implement a custom HttpSessionListener as described there.

    To make the solution complete I'm adding the configuration part. Supposed your implementation looks like this:

     public class CustomViewMapConfig implements HttpSessionListener
     {
         @Override
         public void sessionCreated(HttpSessionEvent event)
         {
             event.getSession().setAttribute(ViewScopeManager.ACTIVE_VIEW_MAPS_SIZE, 1);
         }
     }
    

    then the corresponding web.xml looks like this:

    <web-app>
        <listener>
            <listener-class>my.package.CustomViewMapConfig</listener-class>
        </listener>
        ...
    </web-app>