JSF PrimeFaces Tutorial

Filed Under: JSF

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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://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="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://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="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-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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://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>http://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 sample project from above link and play around with it to learn more.

Reference: Primefaces Official Website

Comments

  1. Tom says:

    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

  2. THOUSIF SHAIK says:

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

  3. Rainer says:

    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

  4. Tukiki says:

    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.

  5. HK says:

    Thank you very much!!

  6. marcos ferreira says:

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

  7. viral says:

    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.

  8. Vikram says:

    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

    1. Janelle says:

      I think it has to do with you you’ve configured your tomcat server. Refer here: http://stackoverflow.com/questions/10848341/java-lang-classnotfoundexception-com-sun-faces-config-configurelistener

      Personally, I recommend that you run it on Glassfish instead.

  9. Raichand Ray says:

    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

  10. Jevgenij says:

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

    faces/index.xhtml

  11. Raichand Ray says:

    Dear Sir,
    Your tutorials are very good.Please provide a CRUD (Create,Read,Update,Delete) tutorial using Dao class
    with primeface,jsf,maven and MySQL.Not available in net.

    Thanks

    Raichand

    1. Mohammad says:

      Hi Raichand,

      Actually your request is already provided here at Journaldev as you may reach it easily. You may refer for this tutorial for Pankaj.

      https://www.journaldev.com/7122/jsf-spring-hibernate-integration-example-tutorial

      Thanks again for your follow up and hopefully see you later.

  12. kareem says:

    HI
    you made entitymanager as variable in Facade instead of inject it
    this mean its will be variable of session scoped variable and will be persisted
    but entitymanager is not serialize object and no logic in serializing such object

    Regards,
    Kareem

  13. Norbi says:

    Nice tutorial,
    I hope I finally found some basic knowledge in one place.
    The internet is full of tutorials showing how to generate some Primefaces “code” with wizards, and when you do it is hard to modify the code if you are unaware of how it should be done from the beginning

    I am using netbeans and didn’t want to change IDE just to go through tutorial.
    Not sure was it netbeans related (rather doubt), but came into some issues
    a) couldn’t compile the example, the error I got was: Managed bean declaring a passivating scope must be passivation capable)
    b) I overcome the error by implementing serializable but when compiled and run the employees list was empty
    c) then I finally changed @ManagedBean to @NamedBean and it worked fine

    1. Mohammad says:

      Welcome Norbi,

      Mainly, you have two options to implement what you’re going to do; by using Standard JSF-based annotations or by using their Sun version. CDI (Context Dependency Injection) is a Sun library and you have to use @NamedBean to make such glue you want in your application.

      However, the application above is a maven and it supposed to be cross IDE and of course not relevant for Eclipse. I hope i can help you something better than, but i need a precise question to let me know from where you are suffer.

      Regards,

  14. Arvind says:

    Very detailed Explanation of PrimeFaces 5 for beginner. Good.

  15. Joe B34r says:

    Thanks for the clear “hello world” PrimeFaces tutorial!

  16. SATISH says:

    Hi,
    you shared a very nice information.
    I am beginner in JSF and I am in a development project with JSF.I need some assistance during the development.Please email me your details so that i cen communicate to you and discuss.
    Thanks,
    satish

  17. Amit says:

    Nice tutorial, good for getting started.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages