Home » Java » Enterprise Java » JSF 2.0 Tutorial for Beginners

About Abhishek Kothari

Abhishek Kothari
Abhishek is a Web Developer with diverse skills across multiple Web development technologies. During his professional career, he has worked on numerous enterprise level applications and understood the technological architecture and complexities involved in making an exceptional project. His passion to share knowledge among the community through various mediums has led him towards being a Professional Online Trainer, Youtuber as well as Technical Content Writer.

JSF 2.0 Tutorial for Beginners

1. What is JSF?

JSF is an acronym for Java Server Faces. It is a server side processing technology which allows to embed server side code into a web page. This makes the overall coding for the project simpler as the server side processing and rendering code can be embedded into the webpage itself; reducing the overall count as well as size of files. JSF consists of 2 major components:

  1. Java Facets: Server side files which acts as a controller to redirect the client request to the correct JSF web page.
  2. JSF tags: In addition to allowing server side scripting into the webpage, JSF also provides custom tags to perform certain operations like iterations or condition check easily.

These components collectively form the View and Controller for the MVC.

2. JSF 2.0 – How is it different ?

JSF 2.0 and later versions are a major upgrade from its older version JSF 1.x. With JSF 2.0 version release, the coding style for the JSF based projects took a shift. With JSF 2.0, there is no need to declare different items in separate configuration files like the older version. JSF 2.0 allows to declare almost everything in faces-config.xml file. Moreover, JSF 2.0 has added the functionality to use annotations for defining the navigational, managed or CDI beans. This certainly cuts down the amount of configuration required in order to setup the project structure.

The following sections will provide a basic understanding of how the JSF code works using a simple Hello World example and later move towards JSF 2.0 features and tags.

3. Setting up JSF 2.0 based Dynamic Web Project

3.1 Prerequisites

The examples that follow are created using the below tool set:

  • Maven v4.0
  • Eclipse Java EE IDE
  • Apache Tomcat 9.0
  • JDK v7 or later
  • JSF 2.0

In order to setup the project for performing JSF 2.0 related tasks, start with creating a Maven WebApp project by following the steps shown below.

  1. In Eclipse, Navigate to File -> New -> Maven Project
  2. Select the workspace or choose to use the default workspace and click next

    New Maven Project with default workspace

  3. In the Archetype selection, select maven-archetype-webapp
  4. Provide the Group ID and Artifact ID of your choice and proceed

These steps will create a simple web project with a default index.jsp file in it. Once the project is created, bind the Apache Tomcat server to the project. Once this configuration is done, test run the project by right clicking the file index.jsp and navigating to Run as -> Run on Server. Select Apache Tomcat server and click finish.

A web page similar to the one shown below will be visible if everything is configured fine.

Index Page

The next step is to add the Maven dependencies for JSF 2.0 into the project. Add the following dependencies in the pom.xml to enable support for the JSF 2.0 features.

pom.xml

		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>2.1.7</version>
		</dependency>
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>2.1.7</version>
		</dependency>
		<!-- Required for JSTL tags to be used in JSF -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

Once the dependencies are added into the pom.xml save the project and allow some time for downloading the dependencies.

4. Starting with Managed Beans

One of the major benefit of JSF 2.0 is that it allows use of annotations to define Managed beans. In this section, we cover creation and use of a simple managed bean and later proceed towards slightly complex operations using JSTL tags.

4.1 Creating a simple xHTML page with basic ELs

An EL is an acronym for Expression Language. With JSF 2.0, it is possible to directly access the variables available in the bean or write simple expressions using ELs. Below page contains a simple EL #{'Coding'} which results in a simple string value Coding.

SayHello.xhtml

<!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:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
      
<head>
        <title>JSF 2.0 Say Hello</title>
</head>
    <body>
    	<p>Hey There! My hobby is #{'Coding'}</p>
    </body>
</html>

Before creating the above file in the WEB-INF folder, there are certain configurations that need to be completed.

  1. Configure the project for Java Server Faces by right clicking the project and navigating to Properties -> Project Facets and check the checkbox for JavaServer Faces.
  2. Ascertain the JSF module is 2.0 and not 1.2. If there is a problem in setting it as 2.0, open the file org.eclipse.wst.common.project.facet.core.xml from the folder .settings in the project and add the line
    <installed facet="jst.jsf" version="2.0"/>
  3. Set the Web Module version as 3.0 to enable JSF 2.0 to work smoothly. It can be done by modifying the facet="jst.web" version to 3.0.
  4. Refresh the project once the changes are done.
  5. Right click the project and navigate to Maven->Update Maven Project

Now the project is ready to run. The project structure should look as shown below:

Maven Web App Project Structure

Now just right click the file SayHello.xhtml and navigate to Run as -> Run on Server, select the Apache Tomcat server and click finish to run the first xHTML page.

Notice here that there are 2 different JSF tag libraries imported into the page to support JSF tags. These tags enable to write logical code blocks in the HTML page as well as allow to replace the standard HTML tags with pre-styled JSF tags. On executing the page, the page displays the below output.

Output for SayHello.xhtml

4.2 Creating the first Managed Bean

As a next step, let us take the hobby of the user as a variable in a Managed bean and try to populate it using a managed bean. Create a managed bean using the code below.

HobbiesBean.java

package jsftutorial;

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

@ManagedBean
@SessionScoped
public class HobbiesBean {
	private String hobby = "Java Coding";

	public String getHobby() {
		return hobby;
	}

	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	
}

Notice here that there are two annotations being used.

  1. ManagedBean: This annotation is used to define a managed bean with this simple annotation. A managed bean binds tightly with the page and can be used to fetch the input values from the page or simply put the variable values on the output text.
  2. SessionScoped: This annotation is used to declare the scope of the bean. The scope of the bean decides whether a new instance of the bean will be created each time or not.

Let us try to display the value of variable hobby on the xhtml page created before. In order to do that, modify the SayHello.xhtml file as shown below:

SayHello.xhtml

<!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:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
      
<head>
        <title>JSF 2.0 Say Hello</title>
</head>
    <body>
    	<p>Hey There! My hobby is #{hobbiesBean.hobby}</p>
    </body>
</html>

Once the above code is implemented, restart the server and check the page. The output remains similar except the hobby text. The output would now be Hey There! My hobby is Java Coding. Two points are important to note here.

  1. The bean named used in the above file is hobbiesBean. If noticed carefully, the bean name is similar to the class name except for the first character which is lowercase. JSF 2.0 standards define the bean names automatically by converting the first character into lowercase and leaving the rest of the class name as it is.
  2. The variable hobby is a private variable with getters and setters in the bean. The server uses the getters to get the value of the variable. Hence, the developer is free to manipulate the outputs in the getters if required.

4.3 Naming the bean using a custom alias

The above example uses the default name of the bean as per the JSF standards. However, there could be occasions when the developer would like to use a custom bean name for a better understanding. For instance, for an Employee class, the developer might prefer the bean name to be user. For such scenarios, the annotation @ManagedBean has an attribute name

This attribute allows the developer to give a custom name by using the below syntax. The below modification in the line of code where the annotation is placed will rename the HobbiesBean to myHobbies.

@ManagedBean(name="myHobbies")

Once this change is done in the bean file, modify the SayHello.xhtml file as shown under.

SayHello.xhtml

<!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:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
      
<head>
        <title>JSF 2.0 Say Hello</title>
</head>
    <body>
    	<p>Hey There! My hobby is #{myHobbies.hobby}</p>
    </body>
</html>

The output on execution of this code remains the same despite the change in the name of bean.

4.4 Injecting Bean dependency in Managed Bean

Dependency injection is an important aspect to manage in an object oriented environment. Lets us consider the User class below:

User.java

package jsftutorial;

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

@ManagedBean
@SessionScoped
public class User {
	private HobbiesBean hobby;
	private String name="Java Coder";
	public HobbiesBean getHobby() {
		return hobby;
	}

	public void setHobby(HobbiesBean hobby) {
		this.hobby = hobby;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}	
}

Here we need the object of class HobbiesBean to be injected in the class User. In order to inject it as a managed bean dependency, JSF 2.0 supports the annotation @ManagedProperty(value="#{myHobbies}"). The value attributes should be assigned as per the bean name of the corresponding class. This annotation will automatically inject the dependent bean when the user object is fetched. This can be verified by creating a new file as below.

injectiontest.xhtml

<!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:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
      
<head>
        <title>JSF 2.0 Say Hello</title>
</head>
    <body>
    	<p>Hey There! I am #{user.name}. My hobby is #{user.hobby.hobby}</p>
    </body>
</html>

The output now shows Hey There! I am Java Coder. My hobby is Coding. In this manner, any number of beans could be easily injected without having to initialize the beans.

4.5 JSF 2.0 tags

JSF 2.0 standard defines numerous tags for performing advanced operations in a simple way. As it can be noticed in the xhtml files created above, there are two XML namespaces that have been imported.

xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"

The namespace with the prefix hprovide replacements for regular html tags. A list of the most commonly used tags in relation with their actual HTML tags is provided below.

HTML tagJSF h Tags
<label><h:outputText>
<input type="text"><h:inputText>
<input type="hidden"><h:inputHidden>
<input type="password"><h:inputSecret>
<input type="checkbox"><h:selectBooleanCheckbox>
<input type="radio"><h:selectOneRadio>
<textarea><h:inputTextArea>
<select><h:selectOneListbox>
<select multiple><h:selectManyListbox>
<img><h:graphicImage>

In addition to these, the details of other numerous h tags could be found here.

The namespace with prefix f is important here. The tags provided certain exceptional features like validating components, declaring items for the above htags as well as iterating through objects like list, array or map and creating a data table. Some basic f tags are discussed below with implementation.

actionlistener.xhtml

			
<!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:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
<body>			
<h:form>
<h:commandButton action="result" value="Submit">
    <f:setPropertyActionListener target="#{user.name}" value="Java Code Geeks" />
</h:commandButton>
</h:form>
</body>
</html>

Using the tag f:setPropertyActionListener, it is possible to set the value of a particular property on submit of a form. The above code sets the value of the property name of the user bean when the command button is clicked. This value will be available on the action page result.xhtml. The output is shown below.

Output for f:setPropertyActionListener

Output for f:setPropertyActionListener

Consider the class Bill as shown below.

Bill.java

package jsftutorial;

import java.util.Date;

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

@ManagedBean
@SessionScoped
public class Bill {
	private double amount = 34.8; 
	private Date billDate = new Date();
	public double getAmount() {
		return amount;
	}
	public void setAmount(double amount) {
		this.amount = amount;
	}
	public Date getBillDate() {
		return billDate;
	}
	public void setBillDate(Date billDate) {
		this.billDate = billDate;
	}
}

The next tag being discussed allows to control the number of decimal places in decimal inputs. Create xhtml file as shown below.

convert.xhtml

<!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:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
<body>			

<h:outputText value="#{bill.amount}" >
	<f:convertNumber minFractionDigits="2" />
</h:outputText>

</body>
</html>

This is an extremely useful tag that comes in handy when you wish to truncate a number to certain decimal places or mandate a number to have certain number of decimal places. The use of this tag is extremely simple.
The minFractionDigits mandates minimum number of decimal precision. For instance, if the input entered is 34.8 as is the case with the Bill class, the tag will automatically convert the value to 34.80 as shown in the image below.

Convert Number to minimum 2 decimals

Convert Number to minimum 2 decimals

Similarly, it is also possible to specify the decimal in the form of pattern. For instance:

convert.xhtml

<!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:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
<body>			

<h:outputText value="#{bill.amount}" >
	<f:convertNumber pattern="#00.00" />
</h:outputText>

</body>
</html>

This pattern will allow a maximum of 2 digit number with 2 decimal places. This eliminates any need for adding custom scripts on keyup or focus out. The output remains similar to the one shown above.

convert.xhtml

<!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:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
<body>			

<h:outputText value="#{bill.amount}" >
	<f:convertNumber pattern="#00.00" />
</h:outputText><br>
<h:outputText value="#{bill.billDate}" >
	<f:convertDateTime pattern="d-M-yyyy"/>
</h:outputText>

</body>
</html>

This attribute comes in handy when we need to display the date and time in specific formats. The tag can dynamically accept pattern and display the supplied java.util.Date variable in the given pattern. The bill.billDate is a java.util.Date here. The f tag converts the date into d-M-yyyy format as specified by the java.text.SimpleDateFormat class. The output will be as shown below.

f:convertDateTime to d-M-yyyy format

f:convertDateTime to d-M-yyyy format

For more tags, you can explore them here.

5. Conclusion

The article captures a gist of most of the necessary features of JSF 2.0 to begin with. It begins with the setup process and proceeds with the main feature of using annotations for the managed bean. All the major features like the annotations, h tags and f tags have been covered with necessary details. There is always more to refer. Additional helpful links could be found in the references below.

6. References

7. Download the Eclipse Project

This is an example discussing the use of JSF 2.0.

Download
You can download the full source code of this example here : jsftutorial-1.zip
(0 rating, 0 votes)
You need to be a registered member to rate this.
1 Comment Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Syamsir.1g Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Syamsir.1g
Member

is use maven v4.0 ????