Skip to content
javahacks.dev
JavaServer Faces

JSF Tutorial for Beginners With Facelets and a CDI Bean

Build a first Jakarta Faces 4 page with a Facelets view, a CDI bean and a form, run it on a servlet container and understand what each part does.

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

Jakarta Faces, still widely called JSF, is a component framework for web pages. Instead of writing HTML forms and parsing requests by hand, you write a page in XHTML using Faces tags, bind its fields to properties of a Java bean through expressions, and let the framework convert, validate and call your methods. This tutorial builds the smallest useful application: a greeting form on a Facelets page backed by a CDI bean. It uses Jakarta Faces 4 on Jakarta EE 10 with JDK 21 or later, and it ends by following one click through the framework so the moving parts make sense.

Set up the project

A Faces application is a WAR. The implementation, Mojarra or MyFaces, and CDI come with a Jakarta EE application server such as WildFly or Payara, so the only dependency you compile against is the platform API, marked provided.

pom.xmlXML
<packaging>war</packaging>

<dependencies>
  <dependency>
    <groupId>jakarta.platform</groupId>
    <artifactId>jakarta.jakartaee-api</artifactId>
    <version>10.0.0</version>
    <scope>provided</scope>
  </dependency>
</dependencies>

Add an empty src/main/webapp/WEB-INF/beans.xml with bean-discovery-mode="all" if your server does not discover CDI beans by default, and a faces-config.xml is optional in Faces 4. No web.xml is needed on a Jakarta EE 10 server: the Faces servlet maps itself to *.xhtml automatically, and that is why you open pages by their .xhtml name. If you prefer a plain servlet container such as Tomcat, you must add the Faces implementation and a CDI implementation yourself, which is more work than a server that ships them. The history of the javax to jakarta rename that affects older tutorials is in how Jakarta EE replaced Java EE.

Write the bean

src/main/java/dev/javahacks/web/GreetingBean.javajava
@Named
@RequestScoped
public class GreetingBean {

    private String name;
    private String message;

    public String greet() {
        message = "Hello, " + (name == null || name.isBlank() ? "stranger" : name.strip());
        return null;
    }

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

@Named gives the bean a name for use in expressions: by default the class name with a lower-case first letter, greetingBean. @RequestScoped creates a new instance for each HTTP request and discards it afterwards. The scope decides how long the fields live; a request-scoped bean forgets everything between clicks, which is the safest default, and the options are compared in bean scopes. The action method returns null, which means "stay on the same page". Returning a string would navigate to a view with that name.

Use jakarta.enterprise.context.RequestScoped and jakarta.inject.Named. Tutorials from before 2020 use javax.faces.bean.ManagedBean, which is deprecated and removed in Faces 4, so a page that worked in one of those tutorials will not work here.

Write the page

src/main/webapp/greeting.xhtmlXML
<!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"
                 requiredMessage="Please enter a name"/>
    <h:commandButton value="Greet" action="#{greetingBean.greet}"/>
    <h:messages/>
  </h:form>
  <h:outputText value="#{greetingBean.message}" rendered="#{not empty greetingBean.message}"/>
</h:body>
</html>

The namespaces name the tag libraries. In Faces 4 they start with jakarta.faces.; in Faces 3 and earlier they were URLs under http://xmlns.jcp.org/jsf/, and mixing the two is the first thing that breaks when you copy an old example. h:form is required around any input and command component, because the framework needs a form to submit. #{...} is the expression language: #{greetingBean.name} reads getName() and writes setName(...), so the same expression serves both directions. h:messages shows validation errors.

Run it

Build and deploy the WAR to a running server. On WildFly, copy it to standalone/deployments; on Payara, use asadmin deploy.

Shell
./mvnw package
cp target/greeting.war $WILDFLY_HOME/standalone/deployments/

Open http://localhost:8080/greeting/greeting.xhtml. Click the button with an empty field and the error message appears. Enter a name and the greeting appears below. If the page shows raw #{...} text or the tags unprocessed, the request did not go through the Faces servlet: check that the URL ends in .xhtml and that the application deployed without errors in the server log. If the log says Target Unreachable, identifier 'greetingBean' resolved to null, CDI did not find the bean, and that fix lists the causes.

What happened on the click

Faces processes every request through a fixed lifecycle, and knowing it explains nearly every beginner surprise.

When the browser first requested the page, Faces built a tree of server-side component objects from the XHTML and rendered it as HTML. That tree, or its state, is saved with the page in a hidden field called jakarta.faces.ViewState.

When you clicked the button, the browser posted the form. Faces restored the component tree from the view state, then went through phases: applying the request values to the components, converting and validating them, updating the bean's properties with the validated values, invoking the action, and rendering the response. If validation fails, the model is not updated and the action does not run, which is why leaving the field empty skipped greet(). Each phase is described in the lifecycle.

So the sequence for a valid submission is: setName("Ada") is called, then greet(), then the page is rendered again and getMessage() is called to show the result. Because the bean is request-scoped, a new instance serves the next request, and the message field starts empty.

Four mistakes to avoid early

Putting an input outside h:form makes it silently ignored on submit. Using a @SessionScoped bean for form data keeps old values around between visits and shares state across tabs, so start request-scoped and widen the scope only for data that needs it. Returning a string from an action that matches no view gives a navigation error or an unexpected redirect, so return null to stay. And doing work in a getter is a trap: Faces calls getMessage() several times per request, so a getter that queries the database queries it several times. Load data once, in an action or a @PostConstruct method, and return a field from the getter.

Validation can also be declared on the bean with Bean Validation annotations such as @NotBlank and @Size, which Faces applies automatically, and it keeps the rule in one place instead of repeating required="true" on every page. Messages can be moved into a resource bundle for translation, registered in faces-config.xml, once you have more than one page.

Where the tutorial stops

This is one page, one bean and no navigation, persistence or security. Real applications add a component library such as PrimeFaces, a layout template with ui:composition, converters, AJAX through f:ajax, and a database behind the bean; the choice of libraries is surveyed in JSF and PrimeFaces. Keep business logic out of the bean: it should call a service and shape data for the page. The specification and the platform tutorial give the full detail in the Jakarta Faces specification and the Jakarta EE tutorial.

Also inJakarta EE
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.