Java EE / Jakarta EE

Jakarta Faces (JSF) 4: Components, Life Cycle and CDI Backing Beans

Intermediate10 min readUpdated

Jakarta Faces (JavaServer Faces until the Jakarta rename) is the platform's component-based web framework, and a large amount of enterprise software still depends on it. This guide explains the six-phase request life cycle, how Facelets pages bind to CDI backing beans through the Expression Language, how conversion, validation, navigation and Ajax work, and what Faces 4.0 removed — so you can maintain existing Faces applications confidently and decide when it is still the right tool.

What you will learn

  • Explain the Faces request life cycle and the difference between an initial request and a postback
  • Build a page with Facelets templates, standard components and a CDI backing bean
  • Choose the right bean scope and understand why view-scoped beans must be serialisable
  • Apply converters, validators, Bean Validation and Ajax partial updates
  • Identify what changed in Faces 4.0 and why Faces is considered legacy for new front ends

Jakarta Faces takes a different approach to web user interfaces from anything built on a JavaScript framework: the server keeps a component tree for each page, the browser posts forms back to that tree, and the framework converts, validates and applies the values to Java beans before rendering the next view. If you come from Spring MVC or a REST-plus-React stack, that stateful model explains both why Faces was productive for Java-only teams — no JavaScript, no JSON contracts, type-safe binding to your domain — and why it fell out of favour when single-page applications and horizontal scaling became the norm. A great deal of business software still runs on it, so the goal here is fluency: know what happens on each request, so you can debug it.

Where Faces sits and what it is today

Faces is a servlet. The FacesServlet is mapped automatically to *.xhtml (and to /faces/*, *.faces and *.jsf for older links) as soon as the container detects Faces is in use, so a request for /shop/orders.xhtml goes through the servlet container described in the servlet guide and lands in Faces. Pages are written in Facelets, an XHTML dialect; backing beans are ordinary CDI beans; the Expression Language (EL) connects the two.

Version history matters because the API you see in a codebase tells you its age:

VersionYearHighlights
JSF 1.0 / 1.22004 / 2006JSP views, faces-config.xml for everything
JSF 2.02009Facelets as the default view technology, annotations, implicit navigation, built-in Ajax, view scope
JSF 2.22013HTML5-friendly pass-through attributes, Faces Flows, file upload, stateless views
JSF 2.32017Full CDI integration (@Inject FacesContext), <f:websocket>, date-time support for java.time
Jakarta Faces 3.02020Namespace change to jakarta.faces, no functional change
Jakarta Faces 4.02022@ManagedBean and the jakarta.faces.bean scopes removed, JSP view support removed, short XML namespaces (jakarta.faces.html), automatic extensionless mapping, @ClientWindowScoped

Two implementations exist: Eclipse Mojarra (the compatible implementation, bundled in GlassFish, WildFly and Payara) and Apache MyFaces (bundled in Open Liberty and TomEE). Component libraries — PrimeFaces above all — provide the rich widgets most applications actually use, and OmniFaces fills utility gaps. Tomcat does not ship Faces; you add the implementation and a CDI container yourself, which is one more reason to prefer a Web Profile server for Faces work.

The request life cycle

Understanding the six phases is the single most useful thing you can learn about Faces, because almost every "it does not work" question is really "which phase stopped, and why".

  1. Restore View — for a postback, the saved component tree for the page is restored (from the session by default); for an initial GET, a new tree is built and the life cycle skips straight to Render Response.
  2. Apply Request Values — each input component reads its raw submitted string from the request parameters. Components whose rendered attribute is false are skipped, and action components queue their events here.
  3. Process Validations — submitted strings are converted to the target type and then validated. Any failure adds a FacesMessage, marks the component invalid and causes the life cycle to jump to Render Response: the model is never touched, and no action method runs.
  4. Update Model Values — converted, valid values are written to the bean properties referenced by value="#{bean.property}".
  5. Invoke Application — action methods and action listeners run; the return value of the action decides navigation.
  6. Render Response — the view is rendered to HTML and its state saved for the next postback.

Setting immediate="true" on an input or a command moves its processing to the Apply Request Values phase, which is how "Cancel" buttons bypass validation of the rest of the form. Adding <h:messages globalOnly="false" /> to a page while you develop shows the conversion and validation failures that would otherwise be invisible.

A page and its backing bean

A typical form: an order-search page with a filter, a results table and a button.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="jakarta.faces.html"
      xmlns:f="jakarta.faces.core"
      xmlns:ui="jakarta.faces.facelets">
<ui:composition template="/WEB-INF/templates/layout.xhtml">
  <ui:define name="title">Orders</ui:define>
  <ui:define name="content">
    <h:form id="search">
      <h:messages />
      <h:outputLabel for="customer" value="Customer" />
      <h:inputText id="customer" value="#{orderSearch.customer}" required="true"
                   requiredMessage="Enter a customer name" />
      <h:selectOneMenu id="status" value="#{orderSearch.status}">
        <f:selectItem itemLabel="Any" noSelectionOption="true" />
        <f:selectItems value="#{orderSearch.statuses}" />
      </h:selectOneMenu>
      <h:commandButton value="Search" action="#{orderSearch.search}">
        <f:ajax execute="@form" render="@form results" />
      </h:commandButton>
    </h:form>

    <h:dataTable id="results" value="#{orderSearch.results}" var="o" rendered="#{not empty orderSearch.results}">
      <h:column><f:facet name="header">Id</f:facet>#{o.id}</h:column>
      <h:column><f:facet name="header">Total</f:facet>
        <h:outputText value="#{o.total}"><f:convertNumber type="currency" currencyCode="EUR" /></h:outputText>
      </h:column>
      <h:column><f:facet name="header">Placed</f:facet>
        <h:outputText value="#{o.placedAt}"><f:convertDateTime type="localDate" /></h:outputText>
      </h:column>
    </h:dataTable>
  </ui:define>
</ui:composition>
</html>

The backing bean is a CDI bean. @Named exposes it to EL under the name orderSearch (the class name with a lower-case initial), and @ViewScoped keeps it alive for as long as the user stays on this view, across Ajax postbacks:

package shop.web;

import java.io.Serializable;
import java.util.List;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;

@Named
@ViewScoped                       // jakarta.faces.view.ViewScoped, not the removed jakarta.faces.bean one
public class OrderSearch implements Serializable {

    @Inject
    OrderService orderService;     // a CDI or enterprise bean; transactions live there, not here

    private String customer;
    private OrderStatus status;
    private List<Order> results = List.of();

    public void search() {         // no return value: stay on the same view
        results = orderService.find(customer, status);
    }

    public OrderStatus[] getStatuses() { return OrderStatus.values(); }

    // getters and setters for customer, status, results
}

Note what the bean does not do: it does not open transactions, it does not build SQL and it does not hold the EntityManager. Keep the backing bean as the view model and delegate to a service; the session-bean guide shows what that service looks like.

Choosing a scope

ScopeLives forTypical useCaveat
@RequestScopedOne requestStateless pages, simple forms without AjaxValues are lost between postbacks; conditional rendering based on the bean breaks
@ViewScopedOne view, across postbacks to the same pageMost pages with forms, tables and AjaxMust be Serializable; state stored per view
@FlowScoped("checkout")A multi-page flow with defined entry and exitWizardsRequires flow definition
@SessionScopedThe HTTP sessionLogged-in user, preferencesGrows memory; never for per-page form data
@ApplicationScopedThe applicationReference data, cachesMust be thread-safe
@ClientWindowScoped (4.0)One browser tab or windowTab-specific stateDepends on the client-window mode

View and session scoped beans are passivation-capable: the container may serialise them to disk or replicate them to another node, so every field must be serialisable or transient. An injected enterprise-bean proxy is fine; an injected EntityManager is not.

Facelets: templates, includes and composite components

Facelets pages compose. A template declares insertion points with <ui:insert name="content" />; a page uses <ui:composition template="…"> and fills them with <ui:define>. <ui:include src="…"> pulls in fragments, <ui:param> passes values into them, and <ui:repeat> iterates without generating a table. Anything outside <ui:composition> in a page that uses a template is ignored, which surprises people who add markup at the top of the file.

Composite components let you package a fragment of markup with its own interface under a resource library, so <shop:address value="#{customer.address}" /> becomes a reusable component without writing Java. For anything more complex — custom rendering, JavaScript behaviour — component libraries such as PrimeFaces have usually already done the work.

Two EL details save hours. #{…} is a deferred expression that Faces evaluates during the life cycle and can write back to; ${…} is evaluated immediately during page build and is read-only — in Facelets, use #{…} everywhere. And getters may be called several times per request, once per phase that needs the value, so a getter must be cheap and side-effect free; load data in an action method or a @PostConstruct method and cache it in a field.

Conversion, validation and messages

Every input goes through conversion (string to type) and validation (type-level rules) before it reaches the model. Standard converters exist for numbers and dates (<f:convertNumber>, <f:convertDateTime> with java.time support since 2.3), and Faces resolves converters automatically for primitives, enums and BigDecimal. For your own types, implement Converter<T> and register it with @FacesConverter(forClass = Money.class); Faces 2.3+ lets converters and validators be CDI beans with @FacesConverter(managed = true) so they can inject services.

Validation has three layers, applied in this order:

  1. required="true" — checked before conversion; empty strings are treated as null by default only if jakarta.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL is set, which almost every application should do.
  2. Faces validators — <f:validateLength>, <f:validateLongRange>, <f:validateRegex>, <f:validateBean> and custom @FacesValidator classes.
  3. Bean Validation — constraints such as @NotBlank or @Size(max = 100) on the bean property are validated automatically when a Bean Validation provider is present, which it always is on a Jakarta EE server. This keeps the rules in one place shared with your REST layer and JPA entities.

Failures become FacesMessage objects attached to a component id; <h:message for="customer" /> shows one, <h:messages /> shows all. Application code can add its own with FacesContext.getCurrentInstance().addMessage(...), and messages survive a redirect when you call context.getExternalContext().getFlash().setKeepMessages(true).

Navigation and the Post-Redirect-Get pattern

Since 2.0 navigation is implicit: an action method returning "orders" renders orders.xhtml; returning null or void re-renders the current view. The rendered page and the browser URL, however, diverge after a plain postback — the URL still shows the page that was posted, and a browser refresh resubmits the form. Append ?faces-redirect=true to the outcome (return "orders?faces-redirect=true";) to send a redirect and get a clean GET; add &includeViewParams=true to carry <f:viewParam> values across. Explicit <navigation-rule> blocks in faces-config.xml are still supported, and you will find them in JSF 1.x-era code, but new code rarely needs them.

For bookmarkable pages that load data from the URL, <f:metadata><f:viewParam name="id" value="#{orderView.id}" /><f:viewAction action="#{orderView.load}" /></f:metadata> binds a query parameter and runs a method on the initial GET — the Faces equivalent of a GET controller method.

Ajax without JavaScript

<f:ajax> nested in a component turns its default event (click for buttons, change for inputs) into a partial postback. execute names the components whose values are submitted and processed (@this, @form, @all, or ids), and render names those re-rendered from the response. The whole life cycle still runs on the server for the executed subtree, so validation, model update and the action method behave exactly as in a full postback; only the transport and the DOM update differ. The ids in render must resolve relative to the naming container — a component inside h:form id="search" has the client id search:customer — and an id that does not exist fails at render time with a clear message, whereas an id that exists but is not rendered (because rendered="false") silently updates nothing. Wrap conditionally rendered regions in an always-rendered <h:panelGroup id="wrapper"> and render that.

Why Faces is legacy, and what still argues for it

The model has real costs. State per view in the session limits horizontal scaling unless you use client-side state saving or sticky sessions. Every interaction is a round trip to the server; rich client behaviour means fighting the framework or leaning on a component library's JavaScript. Testing a Faces page means an integrated test with a browser or a container. And the front-end job market has moved to TypeScript frameworks, so hiring for Faces is harder every year.

The case for keeping — or occasionally choosing — it: teams that are entirely Java, internal applications where a component library covers all the widgets needed, no separate API contract to maintain, and security handled by the server rather than by a token flow. If you are building a new public-facing product, use a JavaScript framework against Jakarta REST endpoints. If you maintain a Faces application, keep it on a supported implementation (Faces 4.x with PrimeFaces 13+), move any remaining @ManagedBean classes to CDI, and resist the urge to add JavaScript that bypasses the component tree.

Common mistakes

  • @ViewScoped bean that is not Serializable. Works on one node, fails under session replication or passivation with NotSerializableException. Implement Serializable and mark non-serialisable fields transient.
  • Doing work in getters. A getter hitting the database runs several times per request and again per Ajax call. Load in an action or @PostConstruct.
  • rendered condition on a request-scoped bean. During Apply Request Values the bean is a fresh instance, the condition is false, and the button's action never fires. Use @ViewScoped.
  • Command component outside <h:form>. Nothing is submitted; Development stage warns about it.
  • Nested forms. Invalid HTML; the browser submits the wrong one. One form per logical submission, several forms per page.
  • Wrong Ajax render target. Render an always-present wrapper, not the conditionally rendered component itself.
  • Storing page state in the session. Leads to stale data between tabs and memory growth. Use view scope for page state and session scope for the user only.
  • Forgetting faces-redirect=true. URL lags one page behind and refresh resubmits the form.

Key takeaways

  • Faces keeps a component tree on the server and runs a six-phase life cycle on every postback; conversion or validation failures skip straight to rendering without touching the model.
  • Facelets pages bind to CDI beans through deferred EL expressions #{…}; Faces 4.0 removed the old @ManagedBean model and JSP views.
  • Use @ViewScoped for page state and make those beans Serializable; keep transactions and persistence in the service layer.
  • Bean Validation constraints on bean properties are validated automatically, and <h:messages> makes failures visible.
  • Return outcome?faces-redirect=true from actions to get Post-Redirect-Get behaviour; use <f:viewParam> and <f:viewAction> for bookmarkable pages.
  • <f:ajax> runs the same life cycle for a subtree and re-renders named components; target ids that always exist.
  • Faces is legacy for new front ends but actively maintained and widely deployed; know the life cycle and you can support it well.

Sources and further reading

Frequently asked questions

Is JSF dead? Should I learn it in 2026?
It is legacy for new user interfaces — most greenfield projects use a JavaScript framework talking to REST endpoints — but it is far from dead. Jakarta Faces 4.0 shipped in 2022, PrimeFaces and MyFaces are actively maintained, and a large installed base of internal business applications runs on it. If you work on enterprise Java you will meet it, and understanding its life cycle makes maintenance far less painful.
What replaced @ManagedBean in Faces 4.0?
CDI. Annotate the class with @Named so it is reachable from EL, and give it a CDI scope: @RequestScoped, @ViewScoped (from jakarta.faces.view), @SessionScoped, @ApplicationScoped, @FlowScoped or @ConversationScoped. The jakarta.faces.bean package and its scopes were removed entirely in 4.0, along with support for JSP as a view technology.
Why is my command button not calling the action method?
The usual causes, in order of frequency: the button is not inside an h:form; a conversion or validation error somewhere in the form silently stopped the life cycle at Process Validations (add an h:messages component to see it); the rendered attribute of the button or a parent evaluated to false during Apply Request Values because its condition lives in a request-scoped bean; or nested forms.
Server-side or client-side state saving?
Server-side (the default) keeps the component tree in the session and sends only a token to the browser, which is safer and lighter on the network but uses server memory per view. Client-side serialises the encrypted tree into a hidden field, which scales horizontally without sticky sessions at the cost of larger pages. Most applications keep the default and cap the number of views per session.