PrimeFaces Tutorial (2024)

PrimeFaces is a powerful JavaServer Faces (JSF) framework that simplifies and enhances the development of user interfaces for Java-based web applications. It offers a rich set of UI components, themes, and tools that streamline the creation of interactive and visually appealing web pages. This tutorial based on Primefaces version 14.0.0-RC1 (March 2024) will show you how to set up, design and deploy a Web application on an Enterprise container such as WildFly.

Primefaces, Maven and WildFly together

Before diving into PrimeFaces, ensure you have the following:

  • WildFly application Server ( or equivalent Jakarta EE Container)
  • Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse
  • Maven or Gradle for dependency management

You can kickstart a Maven Project for WIldFly/Maven and Primefaces using the Eclipse Starter for Jakarta EE which is available here: https://start.jakarta.ee/

Choose as version Jakarta EE 10 ( or the version compatible with your project) and choose as Runtime WildFly:

Primefaces, Maven and WildFly

Choose to Generate the project and unzip it in a folder.

Primefaces libraries

Our basic project is a plain Jakarta EE project. Next step will be including PrimeFaces dependency in our pom.xml:

<dependency>
      <groupId>org.primefaces</groupId>
      <artifactId>primefaces</artifactId>
      <version>${primefaces.version}</version>
</dependency>

Please note that, if you are developing a Jakarta EE 10 application (using jakarta namespace) then you need to specify the following classifier in your dependency:

<classifier>jakarta</classifier>

Read more about Primefaces with Jakarta EE 10 in this article: PrimeFaces with Jakarta EE 10 made simple

Coding an HelloWorld Primefaces application

Our Project set up is ready. Wihtout further ado, we will begin coding our HelloWorld Primefaces application. A Primefaces application, like every JSF application, requires the following layers:

View Layer:

  • XHTML Files: These files contain the UI components, layouts, and presentation logic using Facelets (XHTML-based view definition language).
  • PrimeFaces Components: PrimeFaces provides a rich set of components that are used within XHTML files. These components range from basic input fields to advanced data tables, charts, and more.

Backing Beans

  • Managed Beans: These are Java classes annotated with @ManagedBean or @Named annotations, acting as controllers or backing beans that handle the application’s logic and interact with the view layer.
  • Purpose: serve as a bridge between the UI components (view layer) and the business logic or backend services of an application. Their primary purpose is to manage the application’s state, handle user input, and perform actions based on user interactions within the UI.

Coding the Primefaces View

The purpose of this simple Primefaces application will be capturing the user’s input in a text field and return an anagram of the text in a Label. We will also show messages in the View as response to every request.

Add the following index.xhtml page in the webapp folder of your application:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:jsf="http://xmlns.jcp.org/jsf"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:p="http://primefaces.org/ui">

    <f:view contentType="text/html;charset=UTF-8" encoding="UTF-8">
        <h:head>
            <style>           
                .customPanelGrid  {
                    width: 50%; 
    margin: 0 auto; 
                }
            </style>
        </h:head>
        <h:body>
            <h:form id="helloworld">
                <p:growl id="growl" showDetail="true" />
                <p:panelGrid columns="2"  styleClass="customPanelGrid"  style="border:0px none; background-color:transparent;">
                    <p:row>
                        <p:column  >
                            <p style="font-weight: bold;  font-size: 150%;"> Hello World primefaces</p>
                        </p:column>
                    </p:row>
         
                    <h:outputLabel for="@next" value="Word" />
                    <p:inputText id="word" value="#{bean.word}" label="Word" />
                    <h:outputLabel for="@next" value="Anagram" />
                    <h:outputText id="text" value="#{bean.anagram}" />

                    <p:row>
                        <p:column  >
                            <p>This is a sample Primefaces application which anagrams a word</p>
                        </p:column>
                    </p:row>
            
                    <p:row>
                        <p:column  >
                            <p:commandButton action="#{bean.generateAnagram}" update="text,growl"
                            value="Generate anagram" icon="ui-icon-check" style="width: auto" />
                            
                        </p:column>
                    </p:row>

                     
                </p:panelGrid>
            </h:form>
        </h:body>
    </f:view>

</html>

Here are the key points about the view:

  • The View begins by declaring the namespaces associated with various JavaServer Faces (JSF) and PrimeFaces components. You need to include this in your Primefaces View.
  • We are using styles at different levels: with the style attribute we provide in-line css styling for one HTML component. with the styleClass we refer to a style class available in the current page or in an external css
  • We use a growl component to capture information messages that we generate on the Server side
  • Then we use a PrimeFaces PanelGrid component to display a simple Form with input/output text fields and a command button.
  • Across our View we refer to the backing bean named “bean” which we will define in the next section

Coding the Backing Bean

The following Backing Bean is responsible for generating an anagram of the field anagram which will arrives from the View:

@Named("bean")
@ViewScoped
public class Anagram implements Serializable  {
    private String word;
 
    private String anagram;
 

    public void addMessage(FacesMessage.Severity severity, String summary, String detail) {
        FacesContext.getCurrentInstance().
                addMessage(null, new FacesMessage(severity, summary, detail));
    }

 
    
    public void generateAnagram() {
         
 
        List<Character> characters = new ArrayList<Character>();
        for (char c : word.toCharArray()) {
            characters.add(c);
        }
        StringBuilder output = new StringBuilder(word.length());
        while (characters.size() != 0) {
            int randPicker = (int) (Math.random() * characters.size());
            output.append(characters.remove(randPicker));
        }
        this.anagram = output.toString();
        addMessage(FacesMessage.SEVERITY_INFO, "Info Message", "Anagram generated!");
    }
 
    public String getAnagram() {
        return anagram;
    }
 
    public void setAnagram(String anagram) {
        this.anagram = anagram;
    }
 
    public String getWord() {
        return word;
    }
 
    public void setWord(String word) {
        this.word = word;
    }
}

The backing bean is @Named as “bean” and it contains the logic to anagram the word from the View. Also, it produces a message that the growl Primefaces component will display.

Coding the web.xml descriptor

Here is the web.xml descriptor of our Primefaces application:

<web-app version="3.1" 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-app_3_1.xsd">
 
    <display-name>HelloPrime</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.xhtml</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>jakarta.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
</web-app>

The Faces Servlet is a crucial part of JSF applications. It handles incoming JSF requests, manages the JSF lifecycle, processes components, and interacts with managed beans and navigation rules as defined in JSF applications. Please note that, if using a Java EE version of Primefaces, then you need to use:

<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>

Before deploying an application, here is the project view that this Primefaces tutorial will produce from your IDE:

primefaces stet-by-step tutorial

Deploying the Primefaces application

This Primefaces tutorial includes a project with several option to build and deploy your application:

Run the install goal to build your application which you can then deploy in a Web container

mvn install

The pom.xml file also contains the WildFly Maven plugin to allow direct deployment on WildFly:

mvn install wildfly:deploy

Finally, you can also use WildFly Bootable Jar plugin (available in the pom.xml) to build and start the application with WildFly bootable Jar:

 mvn install wildfly-jar:run

Learn more about WildFly bootable Jar here: Turn your WildFly application in a Bootable JAR

Whatever is your deployment choice, once you access the Root Web context of it you will be able to see the following User Interface:

primefaces tutorial

By Clicking on the “Generate anagram” button you will see the word as an anagram in its text field.

Conclusion

This tutorial provided a glimpse into building a basic web application using PrimeFaces, Maven and WildFly. Feel free to explore more components, themes, and customization options available within PrimeFaces to enhance your web development experience.

Source code for the Primefaces tutorial is available here: https://github.com/fmarchioni/mastertheboss/tree/master/web/primefaces/helloworld-primefaces

Found the article helpful? if so please follow us on Socials