jsf

JSF Application NetBeans Example

Photo of Satya ChoudhurySatya ChoudhuryAugust 8th, 2018Last Updated: May 9th, 2019
0 2,024 9 minutes read

1. Introduction

In this example we will demonstrate how to create aJSF Application inNetBeans. Our application will display a simple form to the user asking to enter their name. When they submit the form we will display a welcome message. The name field is mandatory so leaving it blank will display an error message. First Let’s find out more aboutJSFandNetBeans.

1.1 NetBeans

NetBeansis an Integrated Development Environment (IDE). It’s free,open source and similar toEclipse. It provides all necessary features and tools to developJavaapplications easily and quickly. BesidesJavait provides tools to developHTML,PHPandC/C++ applications out of the box. Its code editor supports multiple languages such asJava,C/C++,XML,HTML,PHP,JavaScript, etc. The language support is extensible through plug-ins. It’s based on a plug-ins mechanism thus allows these features to be activated when needed.

CurrentlyNetBeans is going through the process of becoming anApache Software Foundation project. It’s in incubating stage as of this writing.ApacheNetBeans9 RC1 was released on 28th May. Feel free to visithttp://netbeans.apache.org/ if you are interested to learn more.

For this example, we will useNetBeansversion 8.2. You can download the Java EE bundle fromhttps://netbeans.org/downloads/.

1.2 Java Server Faces (JSF)

Java Server Faces (JSF) is a server-side component-oriented framework that helps in creating rich Java-based web applications. It provides a standard platform for resolving common problems of web application development such as navigation, templating, validation, conversion and page flows. It provides an easier way to separate the presentation (i.e. application user interface) from the behavior (i.e. application logic). This clean separation allows the team members to focus on their respective areas. For example, a UI designer can use theJSFUI components to build the application interface or create a mockup without writing any scripts. The application developer can expand the mockup by binding the UI components to the server-side logic and application code.

JSFis based on Model-View-Controller (MVC) 2 pattern.MVCis all about separation of concerns. The model represents the data. The view is the representation of data. Thecontrolleris the one that ties these two together. The diagram below depicts howMVCworks:

JSF Application NetBeans - Model-View-Controller Pattern
Model-View-Controller Pattern

Controllerreceives, interprets, validates the user request, updates the model, determines the next view and present it to the user.

In aJSFapplication,Faces Servlet represents theController. Models are represented byManaged Beans and Views are represented byFacelets. We will go through each of these parts once we have our base application created byNetBeans.

1.3 Technologies used

For this example, we will use the following tools in a Windows 64-bit platform:

  • NetBeans – 8.2
  • Java – 1.8.0_161
  • JSF Framework – 2.2
  • Apache Tomcat – 9.0.10

1.4 Create a JSF Application in NetBeans

We will use the new project wizard to create aJavaweb application. To do so, click on New Project button on the main toolbar or press Control + Shift + N on windows (Cmd + Shift + N on Mac).

SelectJavaWeb from Categories list and Web Application from Projects list. Press Next.

JSF Application NetBeans - Choose Project
Step 1: Choose Project

Enter a Project Name, Location on your hard disk. Project Folder will be filled automatically based on name and location. Press Next.

JSF Application NetBeans - Name and Location
Step 2: Name and Location

Select a server from the Server dropdown list. In this example we will useApacheTomcat9.0.2. Java EE Version and Context Path should be filled already. Press Next.

JSF Application NetBeans - Server and Settings
Step 3: Server and Settings

This is the step where we tellNetBeansthat we want aJava Server Faces application, so select JavaServer Faces from theframeworkslist. Registered Libraries should be JSF 2.2.

JSF Application NetBeans - Frameworks
Step 4: Frameworks

Configuration tab is where one defines theURLpattern and Preferred page language. We are fine with the defaults for this example. Press Finish.

JSF Application NetBeans - Frameworks - Configuration
Step 4: Frameworks – Configuration

If everything goes well, you will have a project created with the following structure:

JSF Application NetBeans - Project Structure
Project Structure

  • Web Pages – Contains all UI files such asXHTMLFacelets,Stylesheets,JavaScripts, etc. At this point, we have our first page called index.xhtml.
  • WEB-INF contains the web deployment descriptorweb.xml.
  • AllJavafiles resides in Source Packages. We don’t have any right now but soon you will see once we create our firstmanaged bean.
  • Libraries contains allframework,JDKand Server related files. Do note thejavax.faces.jar, which is theJSF 2.2 framework.
  • Configuration Files folder contains – Can you guess? Yes, you are right, it shows all configuration files. Do note these configuration files reside in their own folders.NetBeansis just showing all in one place to make it easier for us.

Project is created successfully but does it work? Let’s find out. Press the Run Project button on the toolbar or press F6. It may ask you to enter the username and password for your server. Take a look at the output panel. The important line we are looking for is highlighted below.

JSF Application NetBeans - NetBeans Output Panel
NetBeans Output Panel

IfNetBeansdidn’t open thebrowseritself then open your favoritebrowser and visithttp://localhost:8080/jsf-app-netbeans-example (assuming your server is running on port 8080). The link is also shown in the output panel (highlighted). You should a simple message “Hello from Facelets” on your browser:

There you go, we have our first basic JSF application. Magic… right? Well, having a goodIDEreally saves time but we are not done yet. Let’s take a quick look at the files that was created by the wizard.

1.4.1 Faces Servlet – The Controller

Faces Servlet is the controller of our JSF application. There is no Java file created cause it’s part of theframework. All you need to do is configure it properly in the web deployment descriptor i.e. web.xml file.

Here is the listing of our web.xml file:

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>    <session-config>        <session-timeout>            30        </session-timeout>    </session-config>    <welcome-file-list>        <welcome-file>faces/index.xhtml</welcome-file>    </welcome-file-list></web-app>
  • Line 03 – 06:Context-param element is used to define the init parameters that is going to be available to anyservletin the web application. By setting thePROJECT-STAGE to development we get extradebuggingsupport
  • Line 07 – 11: First we need to tell the server a little bit about theservlet. We do that by using the element. Here we give the servlet a name and the actual class name. load-on-startup element tells the server to load thisservletwhen the server starts
  • Line 12 – 15: Theservletneeds to be mapped to aURLor URL pattern. To do so, we use element. In our case, allURLthat has faces in it will be sent to this servlet. You can define multiple mapping for aservlet. Other possible mappings are /*.jsf, /*.faces, etc.
  • Line 21 – 23: Welcome file list element defines a list of welcome files. The welcome file is invoked by the server automatically if no file name is specified in theURL. Take a look at ourURL, we haven’t specified any file name but the server is smart enough to show us “Hello Faces Servlet” message. How did it happen? Cause we have defined index.xhtml file as our welcome file so the server is picking it up.

1.4.2 Managed Bean – The Model

We don’t have any so let’s create one. Press the New File button on the toolbar or press Control + N on Windows (Cmd + N on Mac). SelectJava Server Faces under Categories and JSFManaged Bean under File Types. Press Next.

JSF Application NetBeans - Choose File Type
Step 1: Choose File Type

Fill in the Class Name and Java package name. This bean will have default scope i.e. request so no change is required. Press Finish.

JSF Application NetBeans - Name and Location
Step 2: Name and Location

We have to add our own code toGreetingsBean so double click on the file to open it in the editor. We need a field to hold the user name and a new method to bind to the submit button. When user presses the Submit button this method will get executed and returns the string that corresponds to the next page to be displayed.

Want to be a JSF Master ?
Subscribe to our newsletter and download theJSF 2.0Programming Cookbookright now!
In order to get you prepared for your JSF development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

Here is the listing of ourGreetingsBean code:

GreetingsBean.java

package com.jcg.jsfnetbeansexample;import javax.faces.bean.ManagedBean;import javax.faces.bean.RequestScoped;/** * * @author Satya Choudhury */@ManagedBean@RequestScopedpublic class GreetingsBean {    private String userName = "";        /**     * Creates a new instance of GreetingsBean     */    public GreetingsBean() {        System.out.println("Created GreetingsBean instance...");    }        public String getUserName() {        return this.userName.trim();    }        public void setUserName(String userName) {        this.userName = userName.trim();    }        public String greetUser() {        return "greeting";    }}
  • Line 14: We added a new string field calleduserName. This will hold the name entered by the user
  • Line 19-21: Theconstructorwas already created for us by the wizard. We just added a SOP for some logging
  • Line 23-29: The getter and setter method foruserName field
  • Line 31-33: ThegreetUser method will be bound to the “submit” button. Notice the string being returned by the method. This string represents the next view i.e.greeting.xhtml without the file name extension

1.4.3 View – The User Interface

Faceletsis the officialtemplatesystem forJSF 2. You can useJSFcomponents directly within theFaceletswithout any additional development. To do so, you will have to define thenamespacein thehtmlelement. Notice the twonamespacewe have specified in the index.xhtml file. Besides templating,Faceletsallows re-use by including the content resides in a separate file. We have oneFaceletalready created byNetBeanscalled index.xhtml. We don’t have the greeting.xhtml file. Let’s create it.

Press the New File button on the tool bar or press Control + N on Windows (Cmd + N on Mac). SelectJavaServer Faces under Categories andJSFPage under File Types. Press Next:

JSF Application NetBeans - Choose File Type
Step 1: Choose File Type

Enter greeting in File Name. Leave other values as it is. Press Finish.

JSF Application NetBeans - Name and Location
Step 2: Name and Location

NetBeanswill create the file and open it in the editor for further editing. Let’s add our own code.

greeting.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://xmlns.jcp.org/jsf/html">    <h:head>        <title>Greeting</title>    </h:head>    <h:body>        <h:outputLabel><h2>Hi, #{greetingsBean.userName}. Nice to meet you.</h2></h:outputLabel>    </h:body></html>
  • Line 6: Change the page title
  • Line 9: Add a JSF UI component to show our greeting message. Notice that theuserName is bound to the field ingreetingsBean. When we retrieve value to display then thegetUserName() method is called automatically

Finally let’s take a look at the index.xhtml.

index.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://xmlns.jcp.org/jsf/html">    <h:head>        <title>JSF Application NetBeans Example</title>    </h:head>    <h:body>        <h:form>            <h:outputLabel><h2>Hi, what's your name?</h2></h:outputLabel>            <h:inputText maxlength="10" required="true" value="#{greetingsBean.userName}" requiredMessage="Please enter your name."/>            <br/><br/>            <h:commandButton value="Submit" action="#{greetingsBean.greetUser}" />        </h:form>    </h:body></html>
  • Line 6: We changed the page title
  • Line 9-14: We added a form to allow the user enter name and press the submit button
  • Line 10: Shows a label for the input field
  • Line 11: The name input field. It allows a maximum 10 characters. Required attribute makes it a mandatory field. We have specified an error message inrequiredMessage attribute. It will be displayed if user submits the form without entering a name. Do notice that value attribute looks exactly same as in our greeting.xhtml file, however the context is different. Here we are receiving the input thussetUserName() method is called automatically
  • Line 13: The submit button is bound to thegreetUser method. The method is called when user presses the button.

It’s time to see the application in action. Click the Run Project button on toolbar or press F6. It should display the following page:

JSF Application NetBeans - First page of the application
First page of the application

If you enter your name and press Submit button then you should see the page below. The screen shot shows that I entered satya which is my name.

JSF Application NetBeans - Greeting page
Greeting page

If you press the submit button without entering a name then you should see the error message like below.

JSF Application NetBeans - Validation error demonstration
Validation error demonstration

This is the final project structure inNetBeans. You must be wondering about all the extra folders that was not there in the beginning:

  • build – This folder contains all files used byNetBeansduring build process
  • dist – The final application that can be distributed or deployed on the servers
  • nbproject – Project settings related internal files used byNetBeans

JSF Application NetBeans - Final project strucuture
Final project strucuture

2. Summary

In this example, we usedNetBeansnew project wizard to create a simpleJSFapplication quickly. It created all necessary files and configurations for us that we used as the base of our application. We extended the base application by creating our own files and codes. We went through the basic structure of aJSFapplication and what role is played byFaces Servlet,FaceletsandManaged Beans. How it’s mapped toMVC 2 pattern.

3. Download the NetBeans Project

This was an example ofJSFApplication inNetBeans

Download
You can download the full source code of this example here :jsf-app-netbeans-example.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
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 theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Satya ChoudhurySatya ChoudhuryAugust 8th, 2018Last Updated: May 9th, 2019
0 2,024 9 minutes read
Photo of Satya Choudhury

Satya Choudhury

Satya Choudhury is a IT professional with over 23+ years of experience in multiple technologies such as Java, IBM AS/400 (iSeries) and Web (PHP, Vuejs, Codeigniter, Bootstrap, etc.). Apart from programming he also possess excellent UI/UX design skills and runs his own store at http://satyatunes.com.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.