Tutorial

JSF Tutorial for Beginners

Published on August 3, 2022
Default avatar

By Pankaj

JSF Tutorial for Beginners

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 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 https://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 https://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 https://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 https://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 https://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="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>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" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
      xmlns:h="https://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="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-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.

Download JSF Hello World Project

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

Learn more about us


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
September 9, 2020

I made the same code on 3 machines, it works on the first two but not the last any ideas why ?

- lenaraa

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    April 5, 2019

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

    - Andrei Holder

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      March 31, 2018

      Thanks for helping us out mate

      - Sinclair

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 22, 2016

        very helpful, thank you.

        - Dax

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          July 30, 2016

          as always, tutorials from this site never work

          - svorobei

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            August 13, 2015

            superb explanation sir… :) now i got an idea abut jsf :) t q so much …

            - Kamalakannan G

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 4, 2015

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

              - JOHNYBASHA SHAIK

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                February 2, 2015

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

                - solomon

                  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!

                  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