webtier@glassfish.java.net

_at_PreDestroy on a ViewScoped managed bean

From: <webtier_at_javadesktop.org>
Date: Thu, 01 Oct 2009 21:44:08 PDT

I have a managed bean that needs to remove its data listener from an ApplicationScoped data model, and I would like to put the managed bean in View scope. So I need to know when its lifespan is up.

I naively thought that ViewScoped managed beans expire when I change to a different page in the browser, but I see that it's not so simple. If I then use the browser's back (or forward) button the view is still there, maintaining its state. I was also a little surprised to see that the ViewScoped bean survives destroying the session.

Anyway, I put a method with a @PreDestroy annotation on the ViewScoped bean, and also registered a ComponentSystemEventListener on the view root for PreDestroyViewMap events.

In the server logs, I see it create new instances of my bean when I reload the page or follow a link to it, but I have never seen either the PreDestroy method or the listener called. (The PostConstruct method DOES get called).

Am I confused, is there a bug, or do they just live forever? Or is there another way to find out when they expire? Is it possible to have more than one UIViewRoot on the same page concurrently in one session? What triggers their expiration? I haven't found much detail on this, so if anyone knows of any doc, please let me know.

Here's my code for registering the listener. I tried calling it in the bean's constructor and in the PostConstruct method, which does get called.

    private void registerViewListener() {

        FacesContext context = FacesContext.getCurrentInstance();
        UIViewRoot viewRoot = context.getViewRoot();
        viewRoot.subscribeToEvent(PreDestroyViewMapEvent.class, new ViewMapExitHandler());
    }


    public class ViewMapExitHandler
        implements ComponentSystemEventListener, Serializable {

        public ViewMapExitHandler() {}

        public void processEvent (ComponentSystemEvent event) {

            System.out.println("ViewMapExitHandler");
            diagram.setDataModel(null);
            event.getComponent().unsubscribeFromEvent(PreDestroyViewMapEvent.class, this);
        }
    }

Thanks for any help.
[Message sent by forum member 'judys' (judy_at_apprisant.com)]

http://forums.java.net/jive/thread.jspa?messageID=366567