JSF 2 Hello World using Maven

JavaServer Faces (JSF) is a standard Java framework for building user interfaces for Java Web
applications. It combines an MVC design approach with a standard component based UI development framework.

In this tutorial, we will create our first JSF 2 application using Maven. We will have a web page with a text box and a submit button, so when the user types a value inside the text field and click the button, he will be forwarded to another page that will display the submitted text field value.

 

1. Technologies used

  • JSF 2.2.8
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.7
  • Tomcat 7.0

 

2. Project structure

We create a maven based web application project.

JSF2HelloWorldUsingMaven

 

3. JSF 2 dependencies

We add the JSF 2 dependencies in Maven’s pom.xml file.

Then, we run the command : mvn clean install to download JSF 2 libraries and put them into Maven’s local repository.

 

4. Managed Bean

Managed Bean is a Java class registered with @ManagedBean and managed by JSF framework.

It is used as model for UI components and it can be accessed by JSF pages.

It has pairs of getter and setter methods corresponding to each input in the JSF page.

It may contain other methods to add business logic.

To register a managed bean, we can use either annotations or JSF configuration file (faces-config.xml).

In this tutorial, we will use annotations to register our Navigator bean.

File : Navigator.java

 

5. JSF View

We will construct our view using Facelets (pages using XHTML syntax).

File : form.xhtml

#{navigator.name}  means that the input text is linked to the name property in Navigator bean.

The action attribute in the button tag is used to tell the browser where to navigate when the button is clicked.

In this case, when the form is submitted, the value in the input text will be passed to the setName(..) method and the user will be forwarded to result.xhtml 

File : result.xhtml

In this page, the text field value is displayed by calling the getName() method in Navigator bean.

 

6. Web app configuration

Now, we will configure the web server part of our application.

The most important thing to define in web.xml is the Faces Servlet that handles the incoming requests.

We must also define the mappings for the Faces Servlet using the servlet-mapping tag. In our case, we say that all URLs with extensions .xhtml or.jsf will be processed by the Servlet.

File : web.xml

We declared the form.xhtml as the home page.

 

7. Test It

Open the browser and type in : http://localhost:8080/JSF2HelloWorldUsingMaven/form.jsf

JSF2HelloWorldUsingMaven1

Enter some value and hit the submit button.

JSF2HelloWorldUsingMaven2

Voilà!

Download source code