Tutorial

JSF PrimeFaces Tutorial

Published on August 3, 2022
author

Pankaj

JSF PrimeFaces Tutorial

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Welcome to JSF Primefaces tutorial. JavaServer Faces is one of the leading framework that is used these days for implementing Java web application user interface. JSF has componentized web application and especially that part related to the interface, in that all single view in the JSF has been built using a server side tree of components decoded into HTML when it comes to be rendered into browser.

JSF Primefaces Tutorial

The process of rendering the view in JSF does pass through what known as JSF lifecycle. This tutorial isn’t intended for providing you a detailed discussion of how lifecycle works or how could we deal with. It’s just a notification about what you should know about the JSF framework and how get JSF view ready for rendering. JSF Primefaces Tutorial, Primefaces Tutorial, Primefaces, Primefaces example JSF has two major implementations till the time in which the article written, oracle implementation Mojarra and Apache MyFaces implementation. Several JSF libraries has been coming into existence, Richfaces, IceFaces, Primefaces, MyFaces, etc and one of the most lead library that used intensively and has an excellent reputation is Primefaces. Primefaces cellabrate before months ago by releasing the Primefaces 5 which will consider the subject of this tutorial and next coming tutorials. For being able of using the primefaces 5, you must install and configure it into your project. Either you are going to use a simple text editor or an enterprise development environment, by ending of this tutorial you will be ready for discovering the all Primefaces components.

What’s New In JSF 2

As we knew, a JavaServer Faces is a framework for developing rich user interface web pages. JSF has been introduced in several Java Community Request JSR where the final release of JSF 2 was released in Jul, 2009 which contains a set of enhancement and new functionalities. Set of consequences have followed JSF 2 and the final one was JSF 2.2 that released in May 2013. Unlike JSF 1.x, JSF 2.x has been coming with a lot of features like using the annotations for declaring the JSF managed beans, Converters, Validators, Scopes etc. That’s not all the story, JSF 2 had provided a newly scopes like View Scope, Custom Scope, Flow Scope and Conversation Scope and much more. Also, we cannot forget the most amazing feature that added for JSF 2 and it’s an Ajax concept. In JSF 2, Ajax has built into JSF framework inherently. So, any of JSF component can be ajaxified by simply adding the Ajax stuff. Navigation rules also has changed and be much easier as well. Next coming tutorials would cover more about those features that added for JSF 2, while in this tutorial, you’re going to create simple JSF application and a bsic sample of how we could use the Primefaces Tags for implementing certain business scenario.

Used Tools For Completing Tutorial

For getting started discovering this tutorial, you have to use the following development tools.

  1. Tomcat 7
  2. Eclipse IDE
  3. Maven 3
  4. JSF 2 / Primefaces 5

It’s obvious that we’ve used the Tomcat 7 for deploying the application and Eclipse IDE for developing the required components where the Maven used as building tool and for managing dependencies. So, be sure that you are aware of how could be all of these softwares installed and configured into your development machine. Our final project will look like below image. PrimeFaces Example, Primefaces Tutorial, Primefaces, JSF Primefaces Tutorial

Creating Eclipse Project

Eclipse IDE support the development of web project under Dynamic Project umbrella. For creating a dynamic project just follow the below steps:

  • Open Eclipse IDE
  • Right-Click on the project explorer space and select New - Dynamic Web Project

JSF Primefaces, Primefaces Tutorial, Primefaces Example, JSF Primefaces Eclipse

  • Complete the project creation process by setting up the project name, target runtime, source folder, context root, content directory and web.xml

JSF Installation & Configuration

As we’ve mentioned earlier, our goal is to use JSF/Primefaces for developing web application that uses the primefaces user interface component, but for now, all what we had is just a simple dynamic application that needs more steps for being jsf configured. To add a jsf into your project you need to add the jsf facet and making notice that the adding of jsf implementation does help you build a jsf application that uses Mojarra. For adding that facet you need to follow the below steps:

  1. Open the properties window for the created project
  2. From the Project Facets pane, just make the JavaServer Faces checked and follow Further configuration required for completing the configuration
  3. Once you’ve clicked on Further configuration required, JSF Capabilities window must be shown
  4. Adding the jsf implementation library by clicking on Download Library< and select from the opening window JSF 2.2 (Mojarra 2.2.0)

After installing the JSF library, the JSF capabilities window looks like JSF Primefaces Tutorial, Primefaces Example, Primefaces, Primefaces Tutorial By end of this phase, you have a web application with jsf capabilities.

Primefaces 5 Installation

For now, your application is ready for using a JavaServer Faces User Interface, but not using of Primefaces. For being able of using the primefaces, you have to follow the below steps:

  1. Download the required primefaces library from the primefaces official site or from Maven central.
  2. Include the downloaded Primefaces JAR into your lib folder that beneath of WEB-INF folder

Developing Primefaces Application

Now, you project is ready for developing a JSF/Primefaces application as you would see. We are going to create a simple application in which a Primefaces DataTable has consumed a list of Employees from the backing bean. Employees list would be populated by a @PostConstruct special method. Follow the below steps for developing a full JSF/Primefaces application.

  1. Create a managed bean named ViewEmployeesManagedBean
  2. Create a Pojo named Employee that contains EmployeeName and EmployeeId
  3. Create a Primefaces view in order to consume the employees list in the defined managed bean
package com.journaldev.data;

public class Employee {
	private String employeeId;
	private String employeeName;
	public String getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(String employeeId) {
		this.employeeId = employeeId;
	}
	public String getEmployeeName() {
		return employeeName;
	}
	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}
}
package com.journaldev.jsfBeans;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.journaldev.data.Employee;

@ManagedBean
@SessionScoped
public class ViewEmployeesManagedBean {
	private List<Employee> employees = new ArrayList<Employee>();

	public ViewEmployeesManagedBean(){

	}

	@PostConstruct
	public void populateEmployeeList(){
		for(int i = 1 ; i <= 10 ; i++){
			Employee emp = new Employee();
			emp.setEmployeeId(String.valueOf(i));
			emp.setEmployeeName("Employee#"+i);
			this.employees.add(emp);
		}
	}

	public List<Employee> getEmployees() {
		return employees;
	}

	public void setEmployees(List<Employee> employees) {
		this.employees = employees;
	}
}

Notice the use of JSF annotations and and use of PostConstruct annotation to populate the list of employees.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<p:outputLabel value="JournalDev - JSF2/Primefaces Tutorial"></p:outputLabel>
<p:dataTable value="#{viewEmployeesManagedBean.employees}" var="employee">
	<p:column>
		<f:facet name="header">
			<h:outputText value="Employee ID"></h:outputText>
		</f:facet>
		<h:outputText value="#{employee.employeeId}"></h:outputText>
	</p:column>
	<p:column>
		<f:facet name="header">
			<h:outputText value="Employee Name"></h:outputText>
		</f:facet>
		<h:outputText value="#{employee.employeeName}"></h:outputText>
	</p:column>
</p:dataTable>
</html>

Notice the use of dataTable element to create the table from the managed bean properties. PrimeFaces and JSF takes care of passing these to the view page for rendering. If you are from Servlet background, you can easily see that number of steps are cut down - in servlet environment, we first handle the request in servlet, create the model data, set it as attribute in request/session and then forward it to the JSP page to render the response.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xmlns="https://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>JournalDev-PrimefacesWebApplication</display-name>
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>
	<context-param>
		<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
		<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
		<param-value>client</param-value>
	</context-param>
	<context-param>
		<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
		<param-value>resources.application</param-value>
	</context-param>
	<listener>
		<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
	</listener>
</web-app>

Notice that javax.faces.webapp.FacesServlet is the controller class, this is where we plugin JSF into our web application.

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="https://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">

</faces-config>

This is where we provide JSF components configurations such as managed beans, i18n global messages, custom view handlers and custom factory classes. Since we are using annotations and it’s a simple project, there is no configuration done here, but we will see it’s usage in future posts. Now when you will run this, you will get output as shown in below image. JSF Primefaces, JSF Primefaces Tutorial

Convert Into Maven

Maven is the most preferred way to manage the java projects build and dependencies, so here we will see how we can convert it to Maven. Eclipse IDE provide the option to convert your Dynamic Web Project into Maven. Maven will help you controlling and managing the required dependencies. Just right click on the created project and from configure menu select Convert into Maven Project. Once you have changed your project into Maven, you have to add the required dependencies for making the project compilable by the Maven itself. The supposed Maven XML that you gain once you’ve converted the application into Maven project and after adding the required libraries for JSF 2, Primefaces and other is:

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JournalDev-PrimefacesWebApplication</groupId>
	<artifactId>JournalDev-PrimefacesWebApplication</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warSourceDirectory>webapp</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
		<finalName>${project.artifactId}</finalName>
	</build>
	<repositories>
		<repository>
			<id>prime-repo</id>
			<name>PrimeFaces Maven Repository</name>
			<url>https://repository.primefaces.org</url>
			<layout>default</layout>
		</repository>
	</repositories>
	<dependencies>
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<!-- Faces Implementation -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>2.2.4</version>
		</dependency>
		<!-- Faces Library -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>2.2.4</version>
		</dependency>
		<!-- Primefaces Version 5 -->
		<dependency>
			<groupId>org.primefaces</groupId>
			<artifactId>primefaces</artifactId>
			<version>5.0</version>
		</dependency>
		<!-- JSP Library -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
		</dependency>
		<!-- JSTL Library -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.1.2</version>
		</dependency>
	</dependencies>
</project>

And by executing the mvn clean package against the project, you will get a WAR file ready for being deployed against any of the Java EE container. Just deploy and examine.

Summary

This tutorial has introduced how you could use a JSF 2 / Primefaces for implementing a web application user interface. In that, we’ve used Eclipse IDE for achieving that, by creating a dynamic project followed by adding all of required libraries either those mandatory for JSF 2 implementation or those required for using Primefaces components. From next tutorial onwards, we will use Maven to create the project for our examples.

Download PrimeFaces Hello World Project

Download sample project from above link and play around with it to learn more. Reference: Primefaces Official Website

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 13, 2017

Sadly it does not work when i import it in netbeans. HTTP Status 404 - Not Found type Status report messageNot Found descriptionThe requested resource is not available. GlassFish Server Open Source Edition 4.1.1

- Tom

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 8, 2017

    Hello I need a datatable display apllication built with PRIMEFACES 6.0 version using maven in eclipse

    - THOUSIF SHAIK

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      December 5, 2015

      Hi, nice tutorial! BUT: Run As - Run on Server results in a “404 resource not available”. Appending /faces/index.xhtml shows the page but with message “No records found”. I followed the steps in the tutorial! I am using Java SE 8 (1.8.0.66), Primefaces 5.3 and Tomcat v7

      - Rainer

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 4, 2015

        Thank you. But I want to ask you a question: What is the use of faces-config.xml in JSF? Thank you for help me.

        - Tukiki

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          November 8, 2015

          Thank you very much!!

          - HK

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 29, 2015

            Very nice tutorial. It is very well explained. Even being a beginner, I was able to follow it without troubles. Congratulations

            - marcos ferreira

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              August 18, 2015

              I am not able to run the application with wildfly 8.2, my requirement is to use wild fly. I am getting error org.jboss.weld.exceptions.IllegalStateException: WELD-001332: BeanManager method getBeans() is not available during application.

              - viral

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                August 7, 2015

                Thanks for providing beautiful tutorial Can you please help me SEVERE: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/prime-showcase]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) I am getting above exception but i didn’t have any clue… Can you please provide solution on error. Thanks, Vikram P

                - Vikram

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  July 27, 2015

                  Dear Sit, Please provide a simple tutorial involving Maven,Primefaces5,Hibernate4,spring4,Mysql,CRUD with Dao class Displaying table data in primefaces table with google like pagination. Thanks Raichand Ray

                  - Raichand Ray

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    July 23, 2015

                    probably you missed few lines in web.xml (i am using 5.0 primefaces, java 8,): faces/index.xhtml

                    - Jevgenij

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Featured on Community

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel