JSF Tutorial for Beginners

Filed Under: JSF

Welcome to JSF Tutorial for Beginners. Java Server Faces (JSF) technology is a front end framework which makes the creation of user interface components easier by reusing the UI components. JSF is designed based on the Model View Controller pattern (MVC) which segregates the presentation, controller and the business logic.

JSF Tutorial for Beginners

jsf tutorial for beginners

In the Model View Controller pattern, model contains the business logic required to accomplish the business scenario, view represents the presentation layer like the JSP or JSF pages and controller represents the process of handling the control to the model/view depending on the requested operation.

JSF provides the following components to create an user interface:

  • Standard basic input elements like fields, buttons etc. that forms the set of base UI components.
  • Rendering ability of JSF depending on the the client specifications
  • Core library
  • Extending available ui components to add more components and use them for accomplishing client requirements.

JSF Tutorial for Beginners – Environment Setup

Here we will go through all the necessary steps to setup your computer to create first JSF application.

JDK installation

Download the jdk from the following Oracle website

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Set the environmental variable JAVA_HOME pointing to the bin path of the installed jdk. For example “C:\Program Files\Java\jdk1.7.0_60”. Also add JAVA_HOME\bin to the PATH variable so as to locate the java binaries.

Now verify whether java is successfully installed on the machine by typing javac on the command window which should display all the options available or “java -version” which should show the version of java installed on the machine.

For more details, you can go through following post: How to install Java on Windows

IDE installation

Some of the popular IDEs that are available include Eclipse, NetBeans and IntelliJ IDEA. Download eclipse from the following link http://www.eclipse.org/downloads/ and run the downloaded binary file and install eclipse on your machine.

For NetBeans, download NetBeans IDE from https://netbeans.org/downloads/ and complete the installation.

Apache Tomcat Installation

Download tomcat from the following link http://tomcat.apache.org/. Run the downloaded binary file and set the CATALINA_HOME variable to point to the installation path. Now start the server and go to http://localhost:8080 in your favorite browser which displays the default tomcat page if installed successfully.

Our base setup is ready, let’s move on to creating our first JSF application.

JSF Tutorial for Beginners – Hello World Application

Let’s now create a simple hello world JSF web application.

Download the following jars that are essential to execute JSF related code. These can be downloaded from maven central repository http://search.maven.org/. A more lucid way of managing dependencies is by using a build system like maven. For all our examples, we would be using maven. Please refer to the pom.xml for dependencies.

jsf-api-1.2.jar
jsf-impl-2.2.8-04.jar

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<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>com.journaldev.jsf</groupId>
    <artifactId>JSF_HelloWorld</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>JSF_HelloWorld</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1.13</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.1.13</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

JSF Tutorial for Beginners – Create a Managed Bean

A managed bean is a java class registered to JSF which makes interaction between the UI and the business logic possible. Create a managed bean named HelloWorld.java using @ManagedBean annotation as


package com.journaldev.jsf.helloworld;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;


@ManagedBean(name="helloWorld")
@SessionScoped
public class HelloWorld implements Serializable{
    
    private static final long serialVersionUID = -6913972022251814607L;
	
    private String s1 = "Hello World!!";

    public String getS1() {
        System.out.println(s1);
        return s1;
    }

    public void setS1(String s1) {
        this.s1 = s1;
    }
  
}

The @ManagedBean annotation indicates the class HelloWorld is a managed bean. The @SessionScoped bean indicates that the the bean is alive until the HttpSession is valid. Here a string s1 is declared and initialized with “Hello World” and the getter and setter methods are defined to retrieve the value of string s1.

We can provide the bean name also such as @ManagedBean(name="helloWorld"). If no name is provided then it’s derived according to java naming standards. Best practice is to provide the bean name always.

JSF Tutorial for Beginners – View Page

Now create a JSF Page named helloWorld.xhtml which interacts with the HelloWorld bean and retrieves the value through getter method and prints the same in response page.

helloWorld.xhtml


<?xml version='1.0' encoding='UTF-8' ?>
<!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:h="http://java.sun.com/jsf/html">
<h:head>
<title>Hello World JSF Example</title>
</h:head>
<h:body>
       #{helloWorld.s1}
<br /><br />

</h:body>
</html>

Here we call the bean name followed with the string variable declared in the bean as “helloWorld.s1” that fetches the value “Hello World”.

Deployment Descriptor Configuration

Final part is to configure JSF Controller class to handle the client requests. JSF controller servlet is FacesServlet, the final web.xml configuration is given below.

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<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">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<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>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
            30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/helloWorld.xhtml</welcome-file>
</welcome-file-list>
</web-app>

Final JSF Hello world project structure will now look like below in Eclipse.

JSF Hello World Eclipse, JSF Tutorial for Beginners

In the web.xml, we specify the faces config file entry along with mapping servlet for faces, session timeout and the welcome file which gets loaded upon the start of the application.

Once we are done with these changes, we shall run the application which prints the following output in the browser.

JSF Hello World Output, JSF Tutorial for Beginners

That’s all for JSF tutorial for beginners. We will look into different JSF page components in the coming posts. In the mean time, you can download the project from below link and play around with it to learn more.

Comments

  1. Andrei Holder says:

    So much code and so much work for a simple “Hello World”. I am not sure if JSF is the right language for me…

  2. Sinclair says:

    Thanks for helping us out mate

  3. Dax says:

    very helpful, thank you.

  4. svorobei says:

    as always, tutorials from this site never work

    1. Pankaj says:

      Can you tell me the error you are facing? Please follow the steps and do some debugging too. You must have missed some step.

    2. Lele Re says:

      I have not seen code from JournalDev which does not work.
      If you have any problem running it, the blame is on you maties.

      1. Pankaj says:

        Thanks for the kind word friend, you made my day. This kind of support and comments help me keep going on.

        1. Suresh Koumar says:

          Yes the code works and helpful to understand.

    3. Vadim says:

      This project does not work in Intellij. It builds it successfully but how to launch it then?

      1. Pankaj says:

        It’s a web application, deploy it into any servlet container such as Tomcat.

  5. Kamalakannan G says:

    superb explanation sir…… 🙂 now i got an idea abut jsf 🙂
    t q so much ……..

  6. JOHNYBASHA SHAIK says:

    Hi Pankaj, I have a request. Could you please add a index page for JSF when your time permits?

  7. solomon says:

    hi pankaj , nice tutorial i have difficulty in in understanding what Facescontext is and what is its use with example thanks in advance

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