Debug JSF Lifecycle with Custom DebugPhaseListener

This tutorial shows how to debug JSF Lifecycle with a custom DebugPhaseListener. The first place that most developers check for information about where issues are occurring is the application logs. As you are debugging JSF life cycles it can be quite difficult to see in your logs in what phase the errors are occurring. We will show you how you can add some debug information to your logs about the current life cycle events of JSF.

DebugPhaseListener

The DebugPhaseListener implements the PhaseListener which gives us 3 methods to override: beforePhase, afterPhase and getPhaseId. We can configure in what phase these methods are called by specifying a PhaseId in the getPhaseId() method. If we specify PhaseId.ANY_PHASE the beforePhase and afterPhase methods are invoked in every phase. We use these methods to add some logging information before and after each phase.

package com.memorynotfound.jsf;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class DebugPhaseListener implements PhaseListener {

    @Override
    public void beforePhase(PhaseEvent event) {
        if (event.getPhaseId() == PhaseId.RESTORE_VIEW) {
            System.out.println("Processing new Request!");
        }
        System.out.println("before - " + event.getPhaseId());
    }

    @Override
    public void afterPhase(PhaseEvent event) {
        System.out.println("after - " + event.getPhaseId());
        if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) {
            System.out.println("Done with Request!\n");
        }
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
    }
}

Registering the Debug Lifecycle Phase Listener

Before we can use the DebugPhaseListener we must register it in the faces-config.xml. We do this by creating an element of type lifecycle and adding a child element of type phase-listener and providing the fully qualified class name of our DebugPhaseListener.

<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                                  http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd" version="2.2">

    <lifecycle>
        <phase-listener>com.memorynotfound.jsf.DebugPhaseListener</phase-listener>
    </lifecycle>

</faces-config>

Example Output

In this example we access a simple html page without any complex components on the page. We can see that the DebugPhaseListener produced the following output:

Processing new Request!
before - RESTORE_VIEW 1
after - RESTORE_VIEW 1
before - RENDER_RESPONSE 6
after - RENDER_RESPONSE 6
Done with Request!

References

Download

You may also like...