Skip to content
javahacks.dev
JavaServer Faces

JSF Lifecycle Phases Explained With a Debug Listener

Watch the six Faces lifecycle phases run with a PhaseListener, and see why a failed validation skips the action method and why AJAX may run fewer phases.

6 min read
Summarize in AI
Flat illustration of a browser page built from server-side components, with the OpenJDK, Thymeleaf, Vaadin, Spring and CSS logos.

The Faces lifecycle explains behavior that otherwise looks random: the setter that is not called, the action that does not run, the field that keeps the old value. The lifecycle is six named phases, and the quickest way to understand them is to log them. The tutorial where it all starts is the JSF tutorial for beginners, and the framework map is in JSF and PrimeFaces for maintainers.

The six phases

#PhaseWhat happens
1Restore viewBuild or restore the component tree
2Apply request valuesCopy submitted strings onto the components
3Process validationsConvert to the target type and run validators
4Update model valuesWrite valid values into bean properties
5Invoke applicationRun action methods and listeners
6Render responseProduce the page

On an initial GET, only phases 1 and 6 run. Phases 2 to 5 belong to a postback.

Log them with a PhaseListener

src/main/java/dev/javahacks/web/LifecycleLogger.javajava
package dev.javahacks.web;

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

public class LifecycleLogger implements PhaseListener {

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

    @Override
    public void beforePhase(PhaseEvent event) {
        System.out.println("BEFORE " + event.getPhaseId());
    }

    @Override
    public void afterPhase(PhaseEvent event) {
        System.out.println("AFTER  " + event.getPhaseId());
    }
}

Register it in WEB-INF/faces-config.xml:

XML
<faces-config xmlns="https://jakarta.ee/xml/ns/jakartaee" version="4.0">
    <lifecycle>
        <phase-listener>dev.javahacks.web.LifecycleLogger</phase-listener>
    </lifecycle>
</faces-config>

A normal postback of a valid form prints each phase, from RESTORE_VIEW 1 through RENDER_RESPONSE 6. Remove the listener before production: it runs on every request.

What a validation failure looks like

Submit the form from the tutorial with a required field empty. The log shows:

Text
BEFORE RESTORE_VIEW 1
AFTER  RESTORE_VIEW 1
BEFORE APPLY_REQUEST_VALUES 2
AFTER  APPLY_REQUEST_VALUES 2
BEFORE PROCESS_VALIDATIONS 3
AFTER  PROCESS_VALIDATIONS 3
BEFORE RENDER_RESPONSE 6
AFTER  RENDER_RESPONSE 6

Phases 4 and 5 are missing. Validation failed in phase three, Faces added a message and jumped to render. The setter was never called and neither was greet(). Add <h:messages /> to the page to see the error, or you will wonder why nothing happens.

Conversion errors follow the same path

A number field that receives abc fails in conversion, which is part of phase three. The message is a conversion message, and again the model is untouched. Custom messages come from converterMessage, validatorMessage and requiredMessage attributes, or a message bundle.

immediate="true"

Marking a component immediate moves its processing to phase two, before the other components' validation. A Cancel button uses it to skip validation of the form:

XML
<h:commandButton value="Cancel" action="#{bean.cancel}" immediate="true" />

Also common: an immediate input that changes which other fields are required. Use it carefully, because the unvalidated values of other inputs are not applied.

AJAX uses the same phases for part of the tree

With <f:ajax execute="name" render="result"> or PrimeFaces process and update, only the components listed in execute go through phases 2 to 4, and only those in render are re-rendered. A field not in execute is not submitted, which explains the bug where a value is lost on an AJAX click.

Where each common bug lives

Most Faces problems belong to one phase, and the phase gives the first place to look.

SymptomPhaseWhat to check
Page shows old values after a postback6The bean scope, and whether a redirect or a new request recreated the bean
Setter never called3 or earlierA conversion or validation error, see h:messages
Action method never called2 to 4Same cause, plus a button outside the form
Action called with the wrong value4The input was not in the processed part of the tree
ViewExpiredException1The view state could not be restored
Value changes in valueChangeListener come too early3The listener runs after validation and before the model update
NullPointerException in a getter during render6An object that a skipped phase should have created

Reading the phase table before opening the code saves the usual hour of printing values at random points in a bean.

Stopping the lifecycle on purpose

Code can leave the normal path. FacesContext.renderResponse() skips the remaining phases and goes to render, and FacesContext.responseComplete() ends the lifecycle without rendering, which is what a file download or a redirect does:

java
public void download() throws IOException {
    FacesContext ctx = FacesContext.getCurrentInstance();
    ExternalContext ec = ctx.getExternalContext();
    ec.responseReset();
    ec.setResponseContentType("application/pdf");
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"report.pdf\"");
    ec.getResponseOutputStream().write(reportBytes());
    ctx.responseComplete();
}

Without responseComplete(), Faces continues to phase six and appends the page markup to the file, producing a corrupt download. That is a frequent mistake in first download buttons.

A converter shows phase three at work

A converter runs during phase three and is the clearest way to see that a string becomes an object before the model is touched:

java
@FacesConverter("moneyConverter")
public class MoneyConverter implements Converter<BigDecimal> {

    @Override
    public BigDecimal getAsObject(FacesContext ctx, UIComponent c, String value) {
        try {
            return new BigDecimal(value.replace(",", ""));
        } catch (NumberFormatException e) {
            throw new ConverterException(new FacesMessage("Enter a number such as 1,250.50"));
        }
    }

    @Override
    public String getAsString(FacesContext ctx, UIComponent c, BigDecimal value) {
        return value == null ? "" : String.format("%,.2f", value);
    }
}

getAsObject runs on the way in and getAsString runs in phase six on the way out. Putting a breakpoint in each shows the two directions of the same field in one request.

viewAction against PostConstruct

A bean method annotated @PostConstruct runs when the bean is created, before view parameters are set in a view-scoped bean. Loading data there with a parameter that has not been injected gives a null. f:viewAction runs in phase five of the initial request, after f:viewParam values are converted and applied:

XML
<f:metadata>
    <f:viewParam name="id" value="#{orderBean.id}" />
    <f:viewAction action="#{orderBean.load}" />
</f:metadata>

Use load() to fetch the order, and keep @PostConstruct for work that does not depend on the request.

The cost of the lifecycle

Every postback restores the component tree, so a page with thousands of components pays for that on every click. Restrict execute and render to the components that need them, and keep the tree small with rendered conditions and paging for tables. Tree size also decides the memory held per session, which is the subject of view state growth.

Using the lifecycle to choose where code goes

The phases give a rule for placing logic. Code that prepares data for display belongs where it runs once per view, in a f:viewAction or an initialisation method, and not in a getter that runs in phase six every time an expression is read. Code that reacts to a user's input belongs in an action or listener method, which runs in phase five after the model is updated. Code that checks input belongs in a validator, which runs in phase three before any bean sees the value.

A bean method that mixes the three, loading data inside a setter or validating inside an action, works until a validation failure skips phase five and the data is never loaded. Splitting the work along the phase boundaries makes each piece run exactly when its inputs are ready, and it makes the failures predictable.

Where this does not apply

Redirects, <f:viewAction> and <f:viewParam> add steps on initial requests that the six-phase picture omits. GET requests to a page with view parameters run through the lifecycle too. The Faces lifecycle chapter of the Jakarta EE tutorial describes the cycle in detail, and the specification defines it. If the first phase fails, see view expiry.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.