jsfjsf-2phaselistener

JSF 2 -- Get instance of a PhaseListener from a managed bean


Is there a way to get the current instance of a PhaseListener via el context or application context?


Solution

  • You can get the phase listeners attached to the UIViewRoot using <f:phaseListener> tag on a page like this:

    List<PhaseListener> phaseListeners = FacesContext.getCurrentInstance().getViewRoot().getPhaseListeners();
    

    It returns a list of the PhaseListener instances attached to this UIViewRoot instance.

    If you want to get all the global phase listeners registered in a faces-config.xml file you can get them from the LifeCycle instance like this:

    FacesContextFactory contextFactory = (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);    
    LifecycleFactory lifecycleFactory = (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
    Iterator<String> lifecycleIds = lifecycleFactory.getLifecycleIds(); 
    while (lifecycleIds.hasNext()) { 
        String lifecycleId = lifecycleIds.next(); 
        Lifecycle lifecycle = lifecycleFactory.getLifecycle(lifecycleId);
        PhaseListener[] phaseListeners= lifecycle.getPhaseListeners();
    }
    

    Documentation UIViewRoot

    Documentation LifeCycle