Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 119 ยท Servlets and JSP

JavaServer Faces (JSF) Basics

Learn Jakarta Faces (JSF) - Facelets pages, CDI managed beans, expression language, the component tree, the six lifecycle phases, validation, converters and navigation, with runnable models.

JavaServer Faces (JSF), now called Jakarta Faces, is the component-based web framework that belongs to the Jakarta EE platform. Frameworks like Spring MVC and Struts are request-based: you write a controller method for each URL and fill a model. JSF works differently. You describe a page as a tree of UI components (input fields, buttons, tables) bound to properties of a Java object, and the framework handles the request cycle for you: it reads submitted values, converts and validates them, stores them in your object, calls your method, and renders the page again.

In this lesson you will learn the main pieces of JSF: Facelets pages, backing beans, the expression language that connects them, the component tree, the six lifecycle phases, validation and conversion, and navigation. A JSF page needs a Jakarta EE server, which can't run on this page, so the real code is read-only and two runnable programs model the parts that are easiest to get wrong: the lifecycle and expression binding. You should have read Jakarta EE Overview and CDI and Enterprise JavaBeans, because JSF beans are CDI beans.

A first page: Facelets

JSF pages are written in Facelets, XHTML files that use tag libraries. The namespace URIs below are the ones from Faces 4 (Jakarta EE 10 and later); older code uses http://xmlns.jcp.org/jsf/html.

XML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="jakarta.faces.html"
      xmlns:f="jakarta.faces.core">
<h:head>
  <title>Greeting</title>
</h:head>
<h:body>
  <h:form>
    <h:outputLabel for="name" value="Your name:"/>
    <h:inputText id="name" value="#{greetingBean.name}" required="true"/>
    <h:commandButton value="Greet" action="#{greetingBean.greet}"/>
    <h:messages/>
  </h:form>

  <h:outputText value="#{greetingBean.message}" rendered="#{not empty greetingBean.message}"/>
</h:body>
</html>

Notice what is not here: no URL for the form, no request.getParameter. #{greetingBean.name} is an EL expression that binds the text field to a property, and action="#{greetingBean.greet}" names the method to call. The server's FacesServlet renders these tags into ordinary HTML (an <input> with a generated name, a <form> with a hidden state field) and handles the post-back.

The backing bean

A backing bean is a plain Java class that holds the data and the actions of one page:

Java
@Named
@RequestScoped
public class GreetingBean {

    private String name;
    private String message;

    public String greet() {
        message = "Hello, " + name + "!";
        return null;                         // null means: stay on this page
    }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getMessage() { return message; }
}

@Named makes the CDI bean visible to EL under the name greetingBean (the class name with a lower-case first letter). The old @ManagedBean annotation was removed in Faces 4.0, so new code always uses CDI. The scope decides how long the instance lives:

Scope Lives for Typical use
@RequestScoped One HTTP request Simple forms, search boxes
@ViewScoped (jakarta.faces.view) While the user stays on the same page, across post-backs Pages with AJAX, wizards, edit forms
@SessionScoped The user's session Login info, shopping cart (keep it small)
@ApplicationScoped The whole application Shared lookups, read-only data

Beans in the @ViewScoped and @SessionScoped scopes must be Serializable. Pick the narrowest scope that works: a session-scoped bean holds memory for every user until the session ends.

Core ideas

  • Component tree. When a page is first requested, Facelets builds a server-side tree of components (UIForm, UIInput, UICommand, ...). Each component knows its id, its current value and its state. The tree is saved (on the server or in a hidden field called the view state) so the next request can restore it.
  • Expression Language. #{...} is a deferred expression: it is evaluated at different times, to read a value when rendering, and to write one when the form is submitted. That is why the property needs both a getter and a setter. A ${...} expression, in contrast, is evaluated once at render time. See JSTL and Expression Language.
  • Post-back. A form submits to the same page. The framework finds which component fired and runs the lifecycle.

The six lifecycle phases

Every post-back runs the same six phases. Knowing them explains most JSF puzzles ("why was my setter not called?", "why does my action not run?").

flowchart LR
    R1["1 Restore view"] --> R2["2 Apply request values"]
    R2 --> R3["3 Process validations"]
    R3 --> R4["4 Update model values"]
    R4 --> R5["5 Invoke application"]
    R5 --> R6["6 Render response"]
    R3 -. "conversion or<br/>validation error" .-> R6

A validation error jumps straight from phase 3 to phase 6, so the model is not updated and the action does not run.

  1. Restore view rebuilds the component tree (or builds it for a first request, which then goes straight to phase 6).
  2. Apply request values copies each submitted string into its component as the submitted value.
  3. Process validations converts each submitted string to the right type (Integer, Date, ...) and runs validators (required, length, custom). A failure adds a message and skips ahead to rendering.
  4. Update model values writes the converted, valid values into the bean properties (the setters run here).
  5. Invoke application calls the action method (greet) and gets the navigation outcome.
  6. Render response produces the HTML, reading values with the getters.

The next program models these phases with a small component tree, a converter and a validator. Run it, then change the age input to see the lifecycle stop early.

Java A model of the JSF lifecycle: conversion, validation, model update, action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In the first two requests no setter ran and save() was never called: the bean was not touched. This is the most important rule of JSF: a failed conversion or validation stops the lifecycle before the model is updated.

Validation and conversion

Faces converts every submitted string to the property's type automatically for numbers, booleans and enums. For dates you add <f:convertDateTime pattern="yyyy-MM-dd"/>, and for your own types you write a Converter. Validation can be declarative on the tag or on the bean:

XML
<h:inputText id="age" value="#{personBean.age}" required="true"
             requiredMessage="Please enter your age">
  <f:validateLongRange minimum="0" maximum="149"/>
</h:inputText>
<h:message for="age" styleClass="error"/>
Java
public class Person {
    @NotBlank @Size(max = 40) private String name;     // Bean Validation works too
    @Min(0) @Max(149)         private Integer age;
}

When the bean has Jakarta Bean Validation annotations, Faces runs them automatically in phase 3. A custom validator is a class marked @FacesValidator (or a method on a bean referenced by validator="#{bean.check}") that throws a ValidatorException with a FacesMessage.

An action method returns an outcome string, which Faces resolves to a page. With implicit navigation, the outcome "result" shows result.xhtml in the same folder, and "result?faces-redirect=true" sends a redirect so a browser refresh does not re-submit the form (Post/Redirect/Get). Returning null or void redisplays the current view.

Java
public String save() {
    service.save(person);
    return "list?faces-redirect=true";       // redirect to list.xhtml
}

A plain link that does not post back uses <h:link outcome="list" value="Back"/>, and <f:viewParam> reads a request parameter (such as ?id=7) into a bean, so pages can be bookmarkable.

Templates, AJAX and component libraries

  • Templates. <ui:composition template="/layout.xhtml"> with <ui:define name="content"> reuses a master layout, much like JSP includes but type-safe.
  • AJAX. <f:ajax execute="name" render="greeting"/> inside a component turns a click or a change into a partial request that updates only the listed components. It runs the lifecycle for only the execute part of the tree.
  • Component libraries. Plain h: tags are basic. Real applications add PrimeFaces, OmniFaces or similar for data tables, dialogs and charts.

Resolving #{bean.property}

The EL engine splits greetingBean.address.city into a bean name and property path, finds the CDI bean by name, and calls getters (getAddress().getCity()) to read, or the last setter to write. The second program is a small resolver that shows both directions and the failure when a setter is missing.

Java How an EL expression reads and writes bean properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

That last error is the one beginners meet as PropertyNotWritableException: an input bound to a property that has only a getter.

JSF today

JSF has a smaller share of new projects than Spring MVC or single-page applications, but it remains a strong choice for form-heavy internal business applications on Jakarta EE servers (WildFly, Payara, Open Liberty, TomEE), where it ships with the server. Its weak spots are the learning curve of the lifecycle, server-side state per user, and URLs that are not RESTful by default. Know the lifecycle and the scopes, and most of the frustration disappears.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the JSF lifecycle, what happens when a converter or validator fails in the Process Validations phase?

    A conversion or validation error adds a FacesMessage and jumps to Render Response. Update Model Values and Invoke Application are skipped, so the bean is not changed.
  2. 2. Why does an input bound with value="#{bean.age}" need both a getter and a setter?

    Deferred #{...} expressions are evaluated at different times. Rendering reads with the getter, and the Update Model Values phase writes with the setter.
  3. 3. Which bean scope fits a page that uses AJAX across several post-backs but should be discarded when the user leaves the page?

    A view-scoped bean lives as long as the user stays on the same view, across AJAX and form post-backs, and is dropped when navigating away.
  4. 4. What does an action method return so that a refresh in the browser does not re-submit the form?

    Adding faces-redirect=true makes JSF send a redirect after the post, which implements Post/Redirect/Get, so reloading the new page does not repeat the POST.

Summary

  • Jakarta Faces (JSF) is the component-based web framework of Jakarta EE: Facelets pages describe a tree of components bound to bean properties with #{...} expressions.
  • Backing beans are CDI beans (@Named plus a scope). @ManagedBean is gone in Faces 4. Choose the narrowest scope: request, view, session or application.
  • Each post-back runs six phases: restore view, apply request values, process validations, update model values, invoke application, render response.
  • Conversion or validation errors skip the model update and the action and re-render the page with messages.
  • Actions return outcome strings for navigation; add ?faces-redirect=true for Post/Redirect/Get.
  • Templates, f:ajax partial updates and component libraries such as PrimeFaces cover the rest of real applications.

Next: Servlet CRUD Web App with Pagination and File Download goes back to the request-based style and builds a complete list, add, edit and delete application.