JSF Tutorial: An Introduction to JSF

banner_JSF

By Chad Darby for Udemy

Looking for more than a beginner’s guide? Take Chad’s full JSF course.

Click to jump to a specific section: 

INTRODUCTION
OVERVIEW
SET UP DEVELOPMENT ENVIRONMENT OVERVIEW
JSF – Behind the Scenes
JSF – Hello World
Creating JSF HTML Forms Overview
JSF Forms and Managed Beans
JSF Forms and Drop-Down Lists


Part 1: INTRODUCTION

Java Server Faces (JSF) is a popular web application framework for Java. It is the standard web application framework for Java EE.

In this tutorial, I will help you quickly get up to speed with JSF. I will demystify JSF and help you understand the essential concepts to get started with JSF web application development.

Here’s an outline of the tutorial series.

  1.  Tutorial Intro
  2. JSF Overview
  3. Setting up Your Development Environment
  4. JSF Hello World
  5. HTML Forms Overview
  6. Text Fields and Drop-Down Lists
  7. Radio Buttons and Checkboxes

I’ve also provided a quick description of each section in the tutorial series.

JSF Overview

The JSF Overview will discuss separately what the JavaServer Faces (JSF) Framework is, what the Model-View-Controller design pattern is and how it helps to provide greater maintainability to JSF, the benefits of JSF and why we’d like to use it, the third-party JSF UI Components, and some JSF resources.

Setting up Your Development Environment

This part of the tutorial will cover the required software for your JSF development environment as well as walk you through the high-level steps in getting your development environment set up.

JSF Hello World

In this portion of the tutorial series, you will learn how to build a “Hello World” program.

HTML Forms Overview

Once you have learned how to create a very simple “Hello World” program, this part will now show you how to create JSF HTML Forms. This tutorial will start with a review of regular HTML forms then discuss the idea of JSF UI components, take a look at a JSF page structure, how to create forms with JSF, and some technical details on JSF Form UI components.

Text Fields and Drop-Down Lists

This part of the tutorial series will discuss how to use JSF Forms and drop-down lists. It will provide you with insight as to what drop-down lists are, a review of the HTML <select> tag, a discussion of some JSF terminology, and a full JSF page example.

Radio Buttons and Checkboxes

This part of the tutorial series will show you how to use JSF forms and radio buttons. The topics include a radio button demo, JSF terminology: selectOneRadio, and a full JSF page example. The section will also cover how to use checkboxes with a checkbox demo, how to use the JSF terminology for selectManyCheckbox, and also a full JSF example.

Once you have completed all these steps in the JSF Tutorial Series, you will be ready to start building your own applications from scratch using JSF.

Part 2: OVERVIEW

In this section, we will cover the following topics:

  1. What is the JavaServer Faces Framework?
  2. The Model-View-Controller Design Pattern
  3. Benefits of JSF
  4. Third-party JSF UI Components
  5. JSF Resources

What is the JavaServer Faces (JSF) Framework?

JSF is a framework for building web applications in Java. There are a number of ways to build web apps like using Servlets and JSP, or you can make use of a framework like Struts, Spring MVC, etc.

However, JSF is the standard web application framework for the Java Enterprise Edition as published by Oracle; thus, it has all the standard specifications for building Web applications using Java.

Since JSF is a very popular framework, many Java development teams use it for building their web applications. Also, hiring managers normally look for this skill when selecting candidates for their developer requirements. So, adding the JSF skill set to your resume is a major bonus.

Model-View-Controller Design Pattern

Another interesting thing about JSF is that it follows some of the industry patterns or standards. JSF is actually based on the Model-View-Controller Design Pattern.

Many other web app frameworks out there today make use of this pattern – e.g., Spring MVC, ASP.Net, etc.

The really nice thing about this is that once you learn JSF and the Model-View-Controller Design Pattern, you will be equipped with the knowledge of these concepts and if you need to move to another framework, you will not have a problem getting up to speed and transferring to the new MVC framework.

Below is a diagram of the Model-View-Controller (MVC) Design Pattern:

image002

With the MVC Design Pattern, you take some key functionality of the application and break it up into smaller components.

In this example, we have a Web Browser that the user will use. When the user hits a link or submits some form data, it will come into the controller. The purpose of the controller is that it will figure out which piece of code needs to execute based on the Web request, so it may need to route the code from submitting the form data to querying a database or maybe sending an email. The controller is like a traffic cop that determines what piece of code needs to execute for a given Web request.

The controller may also access the Model. The Model provides access to any back-end data that you may have. The Model may make a call to a back-end database like MySQL Oracle, or it may even make calls to a Web service. The Model basically handles retrieving or updating of data for you from your back-end service. Once the Controller has the data from the Model, it will pass this data over to the View.

The View is a page for rendering HTML. This may be a page to render the results of a SQL query or a database insert. The View Page at the end comes back as HTML and goes back to the Web Browser.

image003
To recap, Controller routes the request, Model provides access to back-end data, and View renders a view or HTML response. That is the MVC in a nutshell.

Benefits of Using JSF

Why would you want to use JSF? As mentioned earlier, it’s a standard way of building Web application UIs in Java and is part of the standard Java Enterprise Edition (EE). Also, the JSF Framework includes a large number of UI components that provide custom tags that allow you to generate tables, HTML lists or any type of HTML forms. Many of your UI widgets are also available with JSF. Another great thing about JSF is that it is extendable so you can have third-party teams create UI components that you can add into your application.

Moreover, JSF helps you to manage your application state for Web requests. For example, if you’re building a shopping cart application, you may want to keep track of the items that the user added to his shopping cart. Another example is if you’re building an online exam and you want to keep track of the answers that the user gave for each question. If you have several questions for the exam and at the end you would like to give the taker a pass-or-fail score, you will be able to easily manage your application state by using JSF.

Lastly, the most common thing that you’ll use with JSF is validating form data. The user will insert data and submit the form. Here, you can use JSF to perform some validation. This framework has built-in validation rules and allows you to convert the data to different formats based on your requirements.

The above-mentioned benefits are just a few of the many benefits that you will get from using JSF, not to mention its tremendous popularity among Java developers.

Third-party JSF UI Components

Aside from the core UI components provided by JSF, there are additional UI components created by a large group of developers. You can take many of these third-party components that were created by the open source community and include them into your application.

This is an added benefit of using JSF because you not only get to use the basic UI components available through JSF, but you also get to use other components created by other developers for free.

Three of the most popular websites for these UI components are OpenFaces.org, PrimeFaces.org, and RichFaces.org.

image005

You can download their UI components and use these in your projects at any time.

These are all great sites and they have documentation and demos available to help you use their UI components in your web application.

JSF Resources

image006

The official website for JSF is located at http://goo.gl/ktMFjL. This site is hosted by Oracle and it contains tutorials, documentations, list of methods, and articles about JSF. This is always a good place to start when you’re doing work using JSF just so you can see the official documentations.

And because JSF is a popular technology, there is a great deal of online information that you can find about it – even free tutorials – by simply doing a Google search. You can also find some great books on Amazon about JSF.

image007
One word of caution, though, is that if you are looking for a book on JSF, make sure that you get the latest version and not the outdated ones, as there have been many changes from the earlier versions to the latest one, which is version 2.2.

The same goes for training courses. If you are taking a JSF training course, make sure it covers JSF 2.2.

Shameless plug here: I’m the author of a popular JSF course that covers the latest JSF 2.2.

Udemy Course
https://www.udemy.com/jsf-tutorial/

image009

Part 3: SET UP DEVELOPMENT ENVIRONMENT OVERVIEW

We first need to set up our environment for JSF development.

Before we go into the details of the JSF requirements, we need to make sure that you have the Java Development Kit (JDK) installed – not the JRE, but the actual JDK.

If you need help installing the JDK, check out my video.

This video will take you through all the steps in installing the JDK.

For the remainder of this section, I’ll assume you already have the JDK installed.

In this section, we’ll discuss how to install the following software:

  1. Java Application Server – Tomcat
  2. Java Integrated Development Environment (IDE) – Eclipse
  3. JSF JAR Files
  4. Connect Eclipse to Tomcat

Java Application Server

There are many Java Application Servers available, like Tomcat, GlassFish, JBoss, WebLogic, and WebSeer. However, to keep this tutorial simple and straightforward, we are going to make use of the Tomcat server.

I have a video tutorial that shows you how to install Tomcat. Follow this link:

Java Integrated Development Environment (IDE)

Once you have installed Tomcat, the next thing that you will need is a development environment or a Java IDE.

Technically, you can use any other development tool/IDE. You may even use a text editor like TextPad or NotePad, or you may use NetBeans if you prefer. But then again, to keep this tutorial simple, we will focus on just one tool: the Eclipse Development Environment.

I have a video tutorial that shows you how to install Eclipse. Follow this link:

JSF JAR Files

You will need to download the JSF JAR files to be able to create your own applications. JSF is an API, and it has a number of classes and interfaces that you have to use in your projects.

You can manually download the JAR files from Oracle’s website and manually include these in your projects, but there is also a cool and easy way to do it.

In the following sections, I will show you how Eclipse can automatically download the JSF JAR files for you and include them in your project.

So, there’s no action required on your part for now. We’ll cover those steps later.

Connect Eclipse to Tomcat

Lastly, you will need to connect Eclipse to Tomcat. This will allow you to start the Tomcat server from the Eclipse IDE. This configuration will make your life easier during development and testing.

I have a video tutorial that shows how to connect Eclipse to Tomcat.

Part 4: JSF – Behind the Scenes

Before we get into the low-level coding, let’s take a quick peek behind the scenes of JSF.

In this section, we cover the following topics:

  1. The components of a JSF application
  2. How JSF works behind the scenes
  3. Discussion of various JSF versions
  4. Application server support for JSF

Components of a JSF Application

At a very high level, these are the actual components of a JSF application:

Web Page: A JSF application is basically a set of web pages to lay out user interface components. We will make use of a special JSF technology called Facelets.

Beans: A JSF application is also composed of a set of managed beans. This is the Java code that you will have in the background for holding form data. It is also used to perform back-end operations like talking to a database.

Deployment Descriptor: There is also an idea of the web deployment descriptor or a web.xml file. Basically, we put some special configurations in that file to handle JSF requests.

There are also some optional configuration files, like faces-config.xml. Some custom objects, components, custom tags and validators can also be dropped in.

How JSF Works Behind the Scenes

image010

A user submits a request to our application server using their web browser. It will come into our JSF Faces Servlet. The servlet is part of the JSF library, and you don’t have to write it. It handles the routing requests to the appropriate pages.

In the background, the faces servlet can read information from the faces-config.xml file. It can also make use of Managed Beans. These managed beans basically hold the form data. They also talk to the back-end processes like your database.

The faces servlet will determine and route to an appropriate web page – for example, something like hello-world.xhtml. Pages like it can also use the managed bean to retrieve or display information from the back-end system.

At the end, the web page is rendered and sent back to the web browser of the user. It can be simple enough to show some messages on the browser, or it can display something complex like the results of a database query.

JSF Versions

image012

JSF has been around for a long time. There are different versions of it that are floating out there. This course focuses on JSF 2.2.

The first version, JSF 1.0, was released back in 2004 for J2EE 1.4. It was followed by JSF 1.2 in 2006 for Java EE 5, and subsequently by JSF 2.0 for Java EE 6, which was out in 2009. The most recent one, JSF 2.2, was released in 2013 for Java EE 7.

When looking for resources and information on JSF, make sure you get it for at least JSF 2.2. There are some significant changes between version 2.2 and the previous versions. So, beware of outdated information.

Also, make sure that you have an application server that can support JSF 2.2. For that, confirm that your app server supports Java EE 7 or higher.

There’s also a new version of JSF in the works. It will be JSF 2.3. It will come out in early 2017. If you are interested, you can search and follow the release dates and updated news online.

Application Server Support

For choosing an application server, you want to make sure that it supports Java EE7 or higher. Look at the actual specs for your server because not all of them are up to date.

If you make use of the full Java EE7 server, then the JSF 2.2 libraries are already included with it. Some examples of this include JBoss Wildfly 8, GlassFish 4, and so on. They already have full support for Java EE7.

The key thing here is that when you deploy your JSF application; there is no need to include the JSF jar files in your app. It is already a part of the given server environments.

You can also deploy it to a Tomcat 8 server. You simply need to add the JSF libraries to it. JSF 2.2 or higher is preferred. Just bundle the JSF libraries in your application file. For that, include those jar files in your web-inf/lib directory.

Part 5: JSF – Hello World

In this section, we’ll cover the steps to create a Hello World program with JSF.

Development Environment Checkpoint

To build a hello world program, you need to have all of these installed:

  • Apache Tomcat
  • Eclipse (Java EE version)
  • Connected Eclipse to Tomcat

Creating Hello World In JSF

image014

We are going to create a simple hello world program with JSF.

We’ll start with an HTML form in the first page hello-world.xhtml. It will prompt a user for their name. After the user types a name and hits the Submit button, a response page called myresponse.xhtml will say Hello, and then whatever name the user entered.

Download Source Code

The source code for this tutorial is available at the following link:

Creating a New Project In Eclipse

The first thing that we are going to do is create a new project.

1. Open up Eclipse and go to File > New > Dynamic Web Project.

image016

2. It will bring up a dialogue box where you can enter the Project name. Enter the name hello.

image018

3. Make sure that Apache Tomcat is already selected for the Target runtime.

image020

4. In the Configuration section, click the Modify button on the far right to add support for JSF 2.2.

image022

5. In Project Facets, in the middle of the screen there is a link for JavaServer Faces 2.2. Check the box to select it.

image024

6. Hit OK to confirm.

image026

7. Click Next to move to the next step of creating a project.

image028

8. For the output directories, you can keep the default values. Click Next.

image028

9. For the Context root, it is the actual name that we will use in the URL for our application. Keep it as hello. Check the box that says Generate web.xml deployment descriptor. Click Next.

image031

10. Give a reference for the User Library that you will use for JSF. We don’t actually have it on our system from the start. Download it from Oracle’s website, clicking the Download library button present at the far right. It looks like a floppy disk.

image033

11. It will give you a list of libraries that can be downloaded. Select the library JSF 2.2 (Mojarra 2.2.0) that is provided by Oracle Corporation. It will download the files from the official Oracle website to your local file system. Click Next.

image035

12. Accept the terms of license agreement for the download and hit Finish.

image037

13. The actual download process will start. You can see the progress bar for it. Once completed, you will have JSF 2.2 downloaded from Oracle.

14. If you are using Tomcat, check the Include libraries with the application option to include it in your application. If you are using JBoss or GlassFish, you don’t have to include them.

image039

15. Moving down, you will see important settings like JSF Configation File, JSF Servlet Name, JSF Servlet Class Name and URL Mapping Patterns. The faces servlet will have a reference for URL mapping. Anything that comes in /faces/ will be routed through the JSF faces servlet.

image041

16. Hit Finish at the end to complete creating the project. We will have our basic project set up for us.

Creating the HTML Form

Now you have a new project. The first thing that needs to be done is creating an HTML form to allow users to input and submit their name. With JSF, all the pages are written using the .xhtml extension.

1. In Project Explorer, move your mouse to the WebContent folder, right-click on it and select New > HTML File.

image043

2. This new file will be called hello-world.xhtml which will have our actual input form. So, enter the file name as hello-world.xhtml and click Next.

image045

3. You can choose an actual template out of the many available. It is not really important for our example. For now, choose the one that says New Facelet Template and click Finish.

image047

4. Since we’ve chosen a template, it will give us some lines that we don’t need. Select all text, right-click and choose Cut to wipe it. We finally have a blank file.

image049

Add the following code:

<!DOCTYPE html>
    <html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:a="http://xmlns.jcp.org/jsf/passthrough">

    <h:head>
         <title>Hello World - Input Form</title>
    </h:head>
    <h:body>
         <h:form>
             <h:inputText id="name" value="#{theUserName}" a:placeholder="What's your name" />
             <h:commandButton value="Submit" action="myresponse" />
        </h:form>
     </h:body>
</html>

1. The first five lines of code contain the reference for JSF custom tags. JSF has a collection of tags that generates HTML content automatically. We will make use of such tags in our hello-world.xhtml file.

2. After the tag reference, the HTML head section is set up. It is created using HTML custom tags from JSF.

<h:head>
   <title>Hello World - Input Form</title>
</h:head>

3. Then below it is the actual body of the HTML page, which is also built using JSF custom tags. The code for the form is placed between the <h:body> and </h:body> custom tags.
4. This lines of code starting from <h:form> to </h:form> render the form.

image051

5. This code gives us the input text field. It has the id called name. It will bind the value to a request parameter called theUserName. The placeholder is also there to prompt What’s your name on the input box.

<h:inputText id="name" value="#{theUserName}" a:placeholder="What's your name" />

6. This code creates a Submit button. The action is myresponse. So, it will actually submit to a page called myresponse.xhtml.

<h:commandButton value="Submit" action="myresponse" />

This is how the form is set up to take in a name and submit the data to a second page.

Creating the Response Page

Now, let’s create the response page myresponse.xhtml.

1. In the Project Explorer, go to WebContent, right-click on it and select New > HTML File.

image053

2. Enter the File name: myresponse.xhtml and hit Next.

image055

3. Choose New Facelet template and hit Finish.

image057

4. In the newly created file myresponse.xhtml, select and clear all the text. Right-click and choose Cut to remove everything.

image058

Put the following code in the blank file:

<!DOCTYPE html>
<html lang ="en"
   xmlns="http://www.w3.org/1999/xhtml"
   xmlns:h="http://xmlns.jcp.org/jsf/html" >

   <h:head>
     <title>Hello World – Response</title>
   </h:head>
   <h:body>
     Hello, #{theUserName}
   </h:body>
</html>

1. Like in the previous file, we start off with the reference for the JSF custom tag. We are just using a single tag for HTML.

<html lang ="en"
   xmlns="http://www.w3.org/1999/xhtml"
   xmlns:h="http://xmlns.jcp.org/jsf/html" >

2. Next, our basic header is set up, which adds a title to the page.

<h:head>
  <title>Hello World – Response</title>
</h:head>

3. The body comes next. We need to say Hello and we’re going to give the actual user name that was submitted in the HTML form. The code #{theUserName} displays the submitted form data.

<h:body>
   Hello, #{theUserName}
</h:body>

Running The Application

1. Select the file hello-world.xhtml from the Project Explorer. Right-click on it and choose Run As > Run on Server.

image060

2. It will run the application, and we will see it on the browser that is inside of Eclipse. If you look at the URL in the address bar, it is http://localhost:8080/hello/faces/hello-world.xhtml. The /faces/hello-world.xhtml tells us that it is all being passed through the JSF Faces servlet.

image062

3. Type a name in the input box – something like John Doe, for example – and hit Submit.

image064

4. We get the response Hello, John Doe.

image066

5. We can take the URL http://localhost:8080/hello/faces/hello-world.xhtml and try it on a real browser. Copy it and select paste & go in the address bar of your browser. It gives the actual form that we saw earlier in the embedded browser. Type a name like Mary Public and hit Submit.

image068

6. It will give the output Hello, Mary Public.

image070
It works as per our design.

Part 6: Creating JSF HTML Forms Overview

In this section, we cover the steps to create HTML forms using JSF UI components.

We’ll cover the following topics:

  • A review of regular HTML forms
  • The idea of JSF UI components
  • A look at JSF page structures
  • How to create forms with JSF
  • Technical details on JSF Form UI components

Review of HTML Forms

HTML forms are used to get input from the user. We all have used such forms in websites and online applications. They have been around for a long time.

For example: The sign-in page that asks for your user name and password to log into the Facebook is an HTML form.

Whenever you input text and other information into websites, HTML forms are used. We can make use of this same technology with JSF UI components.

JSF UI Components

JSF has components that will generate the HTML for us. To build HTML forms, we can easily make use of JSF UI components.

image072

To build a form, we need a main form container. It is created using h:form. Once the form container is set up, you can add multiple entries like input text, text area, checkboxes, radio buttons, drop-down lists and other form elements.

JSF Page Structure

When you create a JSF page, the most common configuration is to make use of the files that have an .xhtml extension. You get it out of the box when you do a basic installation of JSF. You can also configure it to use different file extensions. To keep it simple, just use the default .xhtml files.

The structure of a JSF page is just a normal HTML page with some special tags mixed in. We can have opening and closing <html> tags along with some regular HTML code that is mixed with JSF tags.

We are also free to use any additional technologies like Cascading Style Sheets 3 (CSS 3) to style elements. We can also add support for JavaScript and use JQuery, or other libraries and frameworks.

So, when you build a page using JSF, you are not limited to using only JSF tags. If you like, you can easily sprinkle in other supporting technologies like CSS and JavaScript functionality.

Creating a Form from Scratch

Switch to Eclipse to create an HTML form.

We can make use of the same project that we have already created for the previous “hello world” project.

Add a new file called simple.xhtml to WebContent. We are trying to create a very simple form that asks someone for their first name and last name along with a submit button.

1. At the beginning, drop the following basic HTML code in the empty file. Notice that xmlns:h="http://xmlns.jcp.org/jsf/html" is a reference to the JSF UI component. Once we have it in place, we can use the special JSF tags.

<!DOCTYPE html>
<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
</html>

2. Next, we have to create the head section, which is built using the JSF component h:head. We also wrap the title of the page inside the <title> HTML element.

<h:head>
   <title>Student Registration Form</title>
</h:head>

3. Then we have the actual body section, which uses the h:body UI component. Some components are visible, and some are not. JSF will handle rendering the appropriate HTML for you.

<h:body>
</h:body>

4. Inside the body tags, we set up the actual form using the opening and closing h:form tags. It builds the basic form container.

<h:form>
</h:form>

5. We need to add in form elements within the form container. For input boxes we make use of h:inputText. It will give a text field where a user can type in some information. We also set a unique id for first name and last name along with value=#{firstName} and value=#{lastName} respectively. The value part sets a request attribute that we can use later in the application.

First name: <h:inputText id="firstName" value="#{firstName}" />
<br/><br/>
Last name: <h:inputText id="lastName" value ="#{lastName}" />
<br /><br/>

6. Moving forward, we put in a reference for the submit button. In the JSF world, they call it a commandButton. The value="Submit" part will actually place a text called Submit on the button.

<h:commandButton value="Submit" />

Here is the full code for the form:

<!DOCTYPE html>
 <html lang="en"
 xmlns="http://www.w3.org/1999/xhtml"
 xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
   <title>Student Registration Form</title>

</h:head>
   <h:body>
     <h:form>
         First name: <h:inputText id="firstName" value ="#{firstName}" />
         <br/><br/>
         Last name: <h:inputText id="lastName" value ="#{lastName}" />
         <br /><br/>
         <h:commandButton value="Submit" />
     </h:form>
   </h:body>
</html>

Running The Application

1. Right-click on simple.xhtml in the Project Explorer and choose Run As > Run on Server. It will start up your local Tomcat server and process the page.

image074
2. A URL like http://localhost:8080/hello/faces/simple.xhtml will open in the embedded browser. It will have the basic form that we set up which asks the user for the first name and last name. It has a submit button below the input boxes.

image076

3. Copy the URL http://localhost:8080/hello/faces/simple.xhtml and then drop it into a real web browser to take a look at it. It looks great in a browser. There are two input boxes and a submit button. You can type in any name, like John Doe. It doesn’t do much because right now there isn’t any real functionality behind it.

image078
How to Reference JSF UI Components

New things have been introduced in JSF 2.2 regarding the XML namespace and referencing it in our .xhtml files. We specify the JSF namespace at the beginning of the file. Older tutorials will have some outdated information. What is new in JSF 2.2 is the actual namespace that you have to use for building the applications.

The important thing to note is that these are unique namespaces that are processed by the server. The namespaces may begin with http:// but there is no requirement to have a real connection to the internet for the UI components to work. The URI is just a unique identifier that is used by the actual server when processing a page.

Here is the list of the URIs:

image080

The namespace listed above is for the Core components, HTML components, Facelets components and Composite components. There are more.

Part 7: JSF Forms and Managed Beans

In this section, we cover the steps to use JSF forms and managed beans.

We’ll cover the following topics

  • What are managed beans?
  • Requirements for creating a managed bean
  • How to create a managed bean with code
  • JSF expression language for accessing managed beans
  • How to set a managed bean property from a JSF page
  • How to read a managed bean property from a JSF page

What Are Managed Beans?

A managed bean is a regular Java class. It is commonly used to hold form data. When a form is submitted, it will hold the form data for you. Managed beans can also be used to hold your business logic.

The main idea here is that the bean is actually created and managed by JSF. You do not have to manually create it with your code. It will be automatically created by the JSF system – hence, the name Managed Bean.

An important thing to note is that managed beans should not to be confused with Enterprise Java Beans (EJBs). They are a totally different technology. Do not mix the two of them up.

image082

The diagram above helps us to better understand how managed beans can be used in a JSF application. The student_form.xhtml is a file where the user will enter form data. Once they hit the submit button, JSF will work behind the scenes to set data on a managed bean and it will hold your form data.

Another page, student_confirmation.xhtml, can access that managed bean and read data from there. Basically, the submitted form data that contains the student’s first and last name will be read. It will also give a confirmation page.

Example: We have a form that asks for the first and last name. We can fill it up with any name, like John Doe.

image084

Once we fill it up and hit the Submit button, in the background, JSF will take that form data, use the managed bean and store the information in there. It will take us to our response confirmation page, which will read the information from the managed bean and display it.

image086

Requirements for Managed Beans

A managed bean is just a regular Java class that needs to have a public no-argument constructor. It also needs to expose properties via public getter and setter methods. Finally, the class should make use of an annotation @ManagedBean. This is a new feature introduced in JSF 2. In previous versions, all the bean configurations were required to be done using a config file.

Creating a Managed Bean

Open Eclipse and access the previous project or the “hello world” project that we have been using so far. If you do not have this beginner project, follow the previous tutorial.

1. We have to create a new Java class in the Java resources directory. In Project Explorer, under the project name hello navigate to Java Resources > src. Right-click on your package, which may have a name like com.luv2ccode.jsf.hello. In the right-click menu, go to New > Class to create a new class.

image088

2. In the New Java Class dialog, give it a name called Student. It will be our managed bean. Then hit the Finish button in the bottom corner.

image090

3. The new Student class will be created and filled with some basic information.

package com.luv2code.jsf.hello;
public class Student{
}

4. Since this is going to be a managed bean, we need to make use of the annotation @ManagedBean.
5. An explicit import should be done for this managed bean. Be very careful in Eclipse, as there are two ManagedBean classesManagedBean(javax.faces.bean) and ManagedBean (javax.annotation). Be sure to use the javax.faces.bean package.

import javax.faces.bean.ManagedBean;

6. Once the proper annotation is imported, create two fields for this class. Create firstName and lastName fields, which are both strings.

 private String firstName;
 private String lastName;

7. The next thing we should do is create a no-argument constructor. Create a constructor by using the same name as the class with a no-return type.

// create no-arg constructor
public Student(){
}

8. Now we have to create getter and setter methods to expose properties. We need to have public getter and setter methods. Instead of manually typing them out, you can use a trick in Eclipse which will automatically generate the source code for you. Just right-click and choose Source > Generate Getters and Setters…

image092
9. It will bring up a dialog box, which will give a list of all of your fields that you have. You have the option to select the ones that you want to create getters and setters with. For our project, choose both firstName and lastName. The rest of the options do not need to be changed, so hit OK.

image094
Eclipse will generate the following code:

public String getFirstName(){
     return firstName;
}
public void setFirstName(String firstName){
     this.firstName = firstName;
}
public String getLastName(){
     return lastName;
}
public void setLastName(String lastName){
     this.lastName = lastName;
}

Until now, we have a public no argument constructor, getter/setter methods and a managed bean. Everything is lined up just right for us.

Here’s the full code for the Student.java file:

package com.luv2code.jsf.hello;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class Student{
       private String firstName;
       private String lastName;
       // create no-arg constructor
       public Student(){
 
       }
       // define getter/setter methods
       public String getFirstName(){
        return firstName;
       }
       public void setFirstName(String firstName){
        this.firstName = firstName;
       }
       public String getLastName(){
        return lastName;
       }
       public void setLastName(String lastName){
        this.lastName = lastName;
       }
}

JSF Expression Language

The JSF Expression language is used to access the properties of a managed bean. You saw this syntax earlier:

#{<beanName>.<property>}

The basic syntax starts with a # and it is followed by a pair of curly brackets. Inside the brackets, we have <beanName>.<property> which allows us to access a particular property. The access is used to read or set the data.

Setting Managed Bean Property from a JSF Page

This is an example of setting a managed bean property from a JSF page using form elements:

<h:inputText value="#{student.firstName}" />

In the example above, we made use of the inputText form component and we say value="#{student.firstName}".

What happens is that when you actually submit the form, JSF will call the property student.setFirstName(). Note the property name that is automatically called.

Getting a Managed Bean Property from a JSF Page

To read or get a bean property using a JSF page, we make use of the JSF expression language as shown in the example below:

Student's name is: #{student.firstName}

The #{student.firstName} is used, which contains the bean name student and the property name firstName. In the background, JSF will actually call student.getFirstName(). Note the property name again. Methods on our Java bean or managed bean are called in the background when the page is processed.

Pulling it All Together

Let us pull this all together in our example code. Our example has two JSF pages: student_form.xhtml for entering the data, and student_confirmation.xhtml for displaying it. We will also make use of the managed bean Student that we created before.

Back in Eclipse, make sure you have these two files: student_form.xhtml and student_response.xhtml inside WebContent > WEB-INF.

Here is the student_form.xhtml file:

<!DOCTYPE html>
<html lang="en"
   xmlns="http://www.w3.org/1999/xhtml"
   xmlns:h="http://xmlns.jcp.org/jsf/html">

   <h:head>
     <title>Student Registration Form</title>
   </h:head>

   <h:body>

   <h:form>
       First name: <h:inputText value="#{student.firstName}" />
       <br/><br/>
       Last name: <h:inputText value="#{student.lastName}" />
       <br /><br />
       <h:commandButton value="Submit" action="student_response" />
    </h:form>
   </h:body>
</html>

The student_form.xhtml file contains a lot of code that we have used before. So, let us go directly into the form which is enclosed between the opening and closing h:form tags – i.e., <h:form></h:form>.

After the labels First name: and Last name: we can see that the JSF UI component h:inputText is used. The values are #{student.firstName} and #{student.lastName} respectively.

When we submit the form data, in the background, JSF will call student.setFirstName() and student.setLastName() methods.

At the end, we can see that our submit button is created using the JSF UI component h:commandButton. The action="student_response" part tells the code to call the student_response.xhtml confirmation page.

Now, switch to the student_response.xhtml file. Here are its contents:

<!DOCTYPE html>
<html lang="en"
   xmlns="http://www.w3.org/1999/xhtml"
   xmlns:h="http://xmlns.jcp.org/jsf/html">

   <h:head>
     <title>Student Confirmation</title>
   </h:head>
   <h:body>
     The student is confirmed: #{student.firstName} #{student.lastName}
   </h:body>
</html>

This is a simple confirmation page that reads the information from the managed bean that we collected and displays it. Enclosed between <h:body> and </h:body> after the static text The student is confirmed:, we make use of the JSF expression language:

#{student.firstName} will call student.getFirstName()
#{student.lastName} will call student.getLastName()

This is how a simple confirmation page is set up.

Testing the Application

Run it in Eclipse. Get the URL and paste it into a browser. We get the form that asks for First name and Last name. Input something like John Doe. Hit the Submit button.

image096

The confirmation page will display the following result. Notice how it displayed the entered data by making use of the managed bean in the background.

image098

Part 8: JSF Forms and Drop-Down Lists

In this section, we cover the steps to use JSF forms and drop-down lists.

We’ll cover the following topics:

  • What drop-down lists are
  • Review of the HTML <select> tag
  • Discussion of some JSF terminology
  • A full JSF page example

What Are Drop-Down Lists?

A Drop-Down List is a part of a form that lists a number of choices. It is one way to allow users to choose between multiple options.

We all have seen these before. We can scroll through the list and select the one choice that matches for us. Your selection is set in the form or drop-down list. You can continue filling up the rest of the information and then submit the form.

Example: A drop-down list where you select your country out of the many available.

Review of the HTML <select> Tag

In HTML, we create drop-down lists with the help of the <select> tag.

<select name="country">
  <option>Brazil</option>
  <option>France</option>
  <option>Germany</option>
  <option>India</option>
  …
</select>

We have a HTML tag called <select> for which we can set a name. Between the opening and closing select tags, we embed a list of options. Each item on the list is placed between its own opening and closing option tags.

In the example above, the name of the tag is country and we have options like Brazil, France, Germany and India.

The above snippet will give us a list that looks something like the one in this form:

image100

JSF Terminology

In the JSF world, a drop-down list is represented by the tag <h:selectOneMenu>. Like its name, it allows us to select one item from a menu.

Using the <h:selectOneMenu>

Putting this together in JSF:

<h:selectOneMenu value="#{studentTwo.country}">
     <f:selectItem itemValue="Brazil" itemLabel="Brazil" />
     <f:selectItem itemValue="France" itemLabel="France" />
     <f:selectItem itemValue="Germany" itemLabel="Germany" />
     <f:selectItem itemValue="India" itemLabel="India" />
     <f:selectItem itemValue="Turkey" itemLabel="Turkey" />
     <f:selectItem itemValue="United Kingdom" itemLabel="United Kingdom" />
     <f:selectItem itemValue="United States" itemLabel="United States" />
</h:selectOneMenu>

After the h:selectOneMenu tag, we give the value="#{studentTwo.country}. It is going to be mapped to a managed bean field.

Then, between the tags we just drop in a list of options. We use the f:selectItem tag and provide an itemValue as well as an itemLabel. itemLabel is the information that will show up on the user’s screen. itemValue is the actual code that you can have for that entry.

In this example, we have used the same itemValue and itemLabel. They can be different, according to what is required.

Pulling it All Together

We are trying to create a form student_two_form.xhtml. Besides the first and last name, we have a new entry for country as a drop-down list. We will also have a managed bean that we will call StudentTwo. We will additionally have a student_two_response.xhtml file that displays the confirmation. It will show the student’s first and last name as well as the selected country.

To-Do List

  • We need to add a new managed bean class called StudentTwo. It will have the firstName, lastName and a new field called country.
  • We will then update the form to make use of the JSF tag <h:selectOneMenu> that generates our drop-down list.
  • We also need to update the confirmation page to display the country that has been selected. It will say something like The student’s country is: India.

In Eclipse, use the existing project “hello” that we have been working on. It was created in one of our previous tutorials.

1. The first thing that we have to do is create a new managed bean. In the Project Explorer, move down to your Java Resources, and right-click on your package to choose New > Class.

image102
2. In the New Java Class dialog, enter the name of the class as StudentTwo. We will give it a unique name. Keep the rest of the options intact, and click on Finish.

image104

3. A basic StudentTwo class is created.

package com.luv2code.jsf.hello;
public class StudentTwo{
}

4. StudentTwo should be a managed bean, so we add and import the correct items.

package com.luv2code.jsf.hello;
import.javax.faces.bean.ManagedBean;
@ManagedBean
public class StudentTwo{
}

5. Now, we need to define our fields for first name, last name and country.

private String firstName;
private String lastName;
private String country;

6. The next thing that we need to do is create a no-argument constructor.

//no-arg constructor
public StudentTwo(){

}

7. Now, we need to generate the getters and setters for our fields. It is done to expose the properties to the JSF system. We can do it automatically with Eclipse. Right-click in the text editor, and choose Source > Generate Getters and Setters…

image106
8. In the dialog box, select all the three fields—country, firstName and lastName. Hit OK.

image108

9. The following new lines of code are added automatically.

public String getFirstName(){
     return firstName;
}
public void setFirstName(String firstName){
     this.firstName = firstName;
}
public String getLastName(){
     return lastName;
}
public void setLastName(String lastName){
     this.lastName = lastName;
}
public String getCountry(){
     return country;
}
public void setCountry(String country){
     this.country = country;
}

We have getter and setter methods for FirstName, LastName, and Country. The bean is now taken care of.

Full Code

Here is the full content of the StudentTwo.java file:

package com.luv2code.jsf.hello;

import.javax.faces.bean.ManagedBean;

@ManagedBean
public class StudentTwo{
     private String firstName;
      private String lastName;
      private String country;
     //no-arg constructor
      public StudentTwo(){
     }
     //getter/setter methods
      public String getFirstName(){
      return firstName;
      }
     public void setFirstName(String firstName){
      this.firstName = firstName;
      }
     public String getLastName(){
      return lastName;
      }
     public void setLastName(String lastName){
      this.lastName = lastName;
      }
     public String getCountry(){
      return country;
      }
     public void setCountry(String country){
      this.country = country;
      }
}

Form Page

Inside the WebContent directory, choose student_two_form.xhtml. Create the file if you need to.

<!DOCTYPE html>
<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
       xmlns:h="http://xmlns.jcp.org/jsf/html"
       xmlns:f="http://xmlns.jcp.org/jsf/core">
      <h:head>
             <title>Student TWO Registration Form</title>
       </h:head>
      <h:body>
            <h:form>
                   First name: <h:inputText value="#{studentTwo.firstName}" />
                   <br/><br/>
                  Last name: <h:inputText value="#{studentTwo.lastName}" />
                   <br/><br/>
                  Country:
                   <h:selectOneMenu value="#{studentTwo.country}">
                         <f:selectItem itemValue="Brazil" itemLabel="Brazil" />
                         <f:selectItem itemValue="France" itemLabel="France" />
                         <f:selectItem itemValue="Germany" itemLabel="Germany" />
                         <f:selectItem itemValue="India" itemLabel="India" />
                         <f:selectItem itemValue="Turkey" itemLabel="Turkey" />
                         <f:selectItem itemValue="United Kingdom" itemLabel="United Kingdom" />
                         <f:selectItem itemValue="United States" itemLabel="United States" />
                   </h:selectOneMenu>
                   <br/><br/>
                  <h:commandButton value="Submit" action="student_two_response" />
            </h:form>
      </h:body>
</html>

The code is pretty much all the standard code that we have been writing up to this point. What is added in this is the code for country. We have set up h:selectOneMenu to display a drop-down menu which lists a number of countries that a user can select. We bind the menu to #{studentTwo.country}. We have listed different values and options under it.

Remember, in the studentTwo class we have a field called country. When the submit button is pressed, the studentTwo.setCountry() method is called. It has the public getter and setter methods to read and write to our managed bean. This is pretty much our form.

At the end we have a submit button and an action which will send it over to a new page, student_two_response.xhtml. We don’t give an extension in the code, as JSF will automatically look for the page.

Confirmation Page

Our confirmation page is student_two_response.xhtml. Navigate to it from the Project Explorer window under the WebContent directory.

<!DOCTYPE html>
<html lang="en"
   xmlns="http://www.w3.org/1999/xhtml"
   xmlns:h="http://xmlns.jcp.org/jsf/html">

   <h:head>
        <title>Student TWO Confirmation</title>
     </h:head>
   <h:body>
   The student is confirmed: #{studentTwo.firstName} #{studentTwo.lastName}
   <br /><br />
 
   The student's country: #{studentTwo.country}
 
   </h:body>
 </html>

After the student’s first and last name confirmation, we have a new line which displays the student’s country.

The value is displayed by #{studentTwo.country}. It will actually talk to the managed bean, call the getter method studentTwo.getCountry() and the results will be displayed on the page.
When you run the application, we are shown a form that asks for a first name, last name and a selectable country in the drop-down menu. Enter the first and last name, choose a country and hit the Submit button.

image110

In the confirmation page, we get the information that is entered: first name, last name and the country that was selected from the drop-down.

image112Download Source Code

The source code for this tutorial is available at the following link:

Summary

This wraps up the JSF tutorial.

In this tutorial we covered the following topics:

  1. Tutorial Intro
  2. JSF Overview
  3. Setting up Your Development Environment
  4. JSF Hello World
  5. HTML Forms Overview
  6. Text Fields and Drop-Down Lists
  7. Radio Buttons and Checkboxes

You now understand the essential concepts of JSF, and you were able to build a JSF web application from scratch.

Do you need to connect JSF to a database?

I am the author of a popular JSF course on Udemy.

The course shows you how to connect JSF to a database. The course includes all source code and database scripts.

You can sign up for the course at:

https://www.udemy.com/jsf-tutorial/

image1124