JSF 2.2 Hello World Tutorial & Example in Eclipse with Maven Support

In this tutorial, let us see how to create a simple hello world web application using JSF 2.x MVC framework in eclipse with maven support. JavaServer Faces (JSF) is part of the Java Platform, Enterprise Edition, that is used for building component-based user interfaces for web applications.

Before continuing to the hello world application, let us understand the some of the basic concepts of a JavaServer Faces (JSF) application that are required to build a simple web application.

1) JSF framework supports the following tag libraries each having different set of tags to add components to the web page.

i) composite
ii) JSF Core (f)
iii) JSF Html(h)
iv) JSTL core (c)
v) JSTL functions (fn)
vi) JSF Facelets (ui)

2) Includes one or more Managed beans (POJOs) each of which can be associated with the components/fields used in a particular page. Annotations like NoneScoped, RequestScoped, ViewScoped, SessionScoped, ApplicationScoped, or CustomScoped are used to define the scope of the managed bean. Default is RequestScoped.

3. javax.faces.webapp.FacesServlet a controller of JSF application that need to be registered in web.xml. FaceServlet a controller servlet is used to dispatch requests to the appropriate view handler. Facelets is the default view handler for JSF 2.x.

4) faces-config.xml,a configuration resource file is created to define page navigation rules, mapping of beans, etc.. Although faces-config.xml is not mandatory for JSF 2.0 and above, it is advised to use for complex navigation.

Now we will create a hello world web application using JSF 2.2 with Maven. It is very simple to create a web application in JavaServer Faces technology.

Technologies used in the project:

JSF 2.2.11
Eclipse
Maven 3.3
Java 1.8
Tomcat

Jars related to JSF

jsf-api
jsf-impl

Developing a simple JavaServer Faces application typically involves the following steps in eclipse

1. Create a Maven Project (JSFDemo)

2. Update pom.xml for downloading necessary JSF dependencies.

3. Create managed bean

4. Create user interfaces (web pages) using component tags

5. Mapping the javax.faces.webapp.FacesServlet instance in web.xml

6. Create application configuration resource file (faces-config.xml)

1. Create a Maven Project (JSFDemo)

jsf maven jsf maven1 jsf maven2

 

Create java folder under src/main

Remove the index.jsp created by default.

2. Update pom.xml with following contents of pom.xml to include necessary dependencies for JSF.

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.javaonline.jsf</groupId>
  <artifactId>JSFDemo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>JSFDemo Maven Webapp</name>
  <url>http://maven.apache.org</url>
   <dependencies>
    <dependency>
	<groupId>com.sun.faces</groupId>
	<artifactId>jsf-api</artifactId>
	<version>2.2.11</version>
    </dependency>

    <dependency>
	<groupId>com.sun.faces</groupId>
	<artifactId>jsf-impl</artifactId>
	<version>2.2.11</version>
	</dependency>

    <dependency>
	<groupId>javax.el</groupId>
	<artifactId>javax.el-api</artifactId>
	<version>3.0.1-b04</version>
	</dependency>

    <dependency>
	<groupId>javax.servlet.jsp.jstl</groupId>
	<artifactId>jstl-api</artifactId>
	<version>1.2</version>
	</dependency>

     <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

	<dependency>
	  <groupId>org.apache.maven.plugins</groupId>
	  <artifactId>maven-compiler-plugin</artifactId>
	  <version>3.3</version>
	  <type>maven-plugin</type>
   </dependency>

  </dependencies>

   	<build>
	 <outputDirectory>src/main/webapp/WEB-INF/classes</outputDirectory>
    <finalName>RESTFUL</finalName>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
			<resource>
				<filtering>false</filtering>
				<directory>src/main/java</directory>
				<includes>
					<include>*</include>
				</includes>
				<excludes>
					<exclude>**/*.java</exclude>
				</excludes>
			</resource>
		</resources>

	</build>

</project> 

3) Create managed bean for HelloWorld application with @ManagedBean annotation (i.e create package net.javaonline.jsf under the folder src/main/java  and create HelloWorldBean.java.


package net.javaonline.jsf;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@ManagedBean(name="helloWorldBean")
//@RequestScoped
@SessionScoped
public class HelloWorldBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private String name;

	public String hello() {

		System.out.println("Calling hellworld.xhtml");

		return "success";

	}

	public String getCurrentTime() {

		return new SimpleDateFormat("dd MMM yyyy:HH:mm:SS").format(new java.util.Date().getTime()); // Older version, SimpleDateFormat is not thread safe
		//return LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd MMM-yyyy HH:mm:ss"));  // Requires Java 8
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

Annotations used

@ManagedBean – To enable HelloWorldBean as Managed Bean

@SessionScoped – means the helloWorldBean lives until the Session is completed. After that it is destroyed.

@RequestScoped – means the helloWorldBean lives until the single request is completed. After that it is destroyed.

4) Create user interfaces (JSF web pages) for Hello World application using component tags. As Facelets views are created as XHTML pages, we will use XHTML technology to build JSF pages.

Let us create two JSF pages, one for input (helloworld.xhtml) and another one for result (result.xhtml) under the folder src/main/webapp.

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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">

<h:head>
<title>My First JSF Application</title>
</h:head>
<h:body>
		<h3>JSF 2.2 Hello World Example</h3>
	<h:form>
		<h3>Now The time is <h:outputLabel> #{helloWorldBean.currentTime}</h:outputLabel></h3>
		Your Name Please?
		<h:inputText value="#{helloWorldBean.name}"></h:inputText>
		<h:commandButton value="Say Hello" action="result"></h:commandButton>
	</h:form>
</h:body>
</html>

To use JSF component tags, declare the below JSF name spaces at top of the page

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">

component tags used in the page

<h:outputLabel> – To create label

<h:inputText> – To create text box

<h:commandButton> – to create button

 

The properties (name & currentTime) of managed bean (helloWorldBean) can be accessed through Expression Language (EL) as given below

#{helloWorldBean.name}, #{helloWorldBean.currentTime}

result.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>JSF 2.2 Hello World </title>
    </h:head>
    <h:body bgcolor="white">
    	<h2>Hi #{helloWorldBean.name} Welcome to JSF Hello World</h2>
    	    	<h2>Now the Time is #{helloWorldBean.currentTime} Bye.</h2>

    </h:body>
</html>

5. Mapping the javax.faces.webapp.FacesServlet instance in web.xml. Update the WEB-INF/web.xml file with the below xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>HelloWorldJSF</display-name>
  <welcome-file-list>
    <welcome-file>faces/helloworld.xhtml</welcome-file>
  </welcome-file-list>
  <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>
  <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>*.xhtml</url-pattern>
  </servlet-mapping>

  <context-param>
    <param-name>javax.faces.CONFIG_FILES</param-name>
    <param-value>
    	WEB-INF/faces-config.xml
    </param-value>
  </context-param>
    <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>

</web-app>

All the JSF pages are logically mapped with the extensions .jsf, .faces, .xhtml so that you can access the pages with any of those extensions.

6. Create application configuration resource file (faces-config.xml)

In faces-config.xml, navigation rules are defined. i.e Mapping of action to JSF pages. In JSF 2.x, you can mention the jsf pages directly in the CommandButton action attribute. So no need to use faces-config.xml. But it is advised to mention navigation rule in faces-config.xml sothat you can understand the project navigation easily.

//To run the above example, you don’t need to copy the below faces-config.xml. If you want to use faces-config.xml, then copy the below faces-config.xml and create another bean called ResultBean as given below. Also create helloworld1.xhtml as given below to run the example using config file.

helloworld1.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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">

<h:head>
<title>My First JSF Application</title>
</h:head>
<h:body>
<h3>JSF 2.2 Hello World Example with faces-config.xml</h3>
<h:form>
<h3>Now The time is <h:outputLabel> #{helloWorldBean.currentTime}</h:outputLabel></h3>
Your Name Please?
<h:inputText value="#{helloWorldBean.name}"></h:inputText>
<h:commandButton value="Say Hello" action="#{resultBean.result}"></h:commandButton>
</h:form>
</h:body>
</html>

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    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-facesconfig_2_2.xsd"
    version="2.2">
<application>
	  <resource-bundle>
		<base-name>JSF Hello World</base-name>
		<var>labels</var>
	   </resource-bundle>
     </application>

     <navigation-rule>
     <from-view-id>/helloworld1.xhtml</from-view-id>
  	<navigation-case>
		<from-action>#{resultBean.result}</from-action>
		<from-outcome>success</from-outcome>
		<to-view-id>/result.xhtml</to-view-id>
		<redirect></redirect>
	</navigation-case>

	</navigation-rule>

</faces-config>

ResultBean.java

package net.javaonline.jsf;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import java.io.Serializable;

//This bean is required if you  use faces-config.xml 

@ManagedBean(name="resultBean")
@RequestScoped   //You can use @ViewScoped
public class ResultBean implements Serializable {

	private static final long serialVersionUID = 1L;

	public String result() {

		System.out.println("Inside Result Bean");
		return "success";

	}

}

The  Complete Project Structure

JSF Hello World Project Structure

 

Now compile and run the above project.

You can call the below Urls to run the project.

http://localhost:8080/JSFDemo/

http://localhost:8080/JSFDemo/faces/helloworld.xhtml

http://localhost:8080/JSFDemo/helloworld.xhtml

http://localhost:8080/JSFDemo/helloworld.jsf

http://localhost:8080/JSFDemo/helloworld.faces

helloworld input helloworld output

 

For Testing with faces-config.xml

call http://localhost:8080/JSFDemo/faces/helloworld1.xhtml
http://localhost:8080/JSFDemo/helloworld1.jsf
http://localhost:8080/JSFDemo/helloworld1.faces

helloworld1 input helloworld1 output

Reference :  JSF HelloWorld

 

You can download the above JSF 2.2 HelloWorld project at  JSFDemo.war

 

 

You may also like

Leave a Reply

4 Comments on "JSF 2.2 Hello World Tutorial & Example in Eclipse with Maven Support"


Guest
Ganesh
7 months 26 days ago

How do I create faces-config.xml , under which project structure, like path I need?

Guest
laxmon
10 months 23 days ago

Please let me know what changes I need to do if i were to deploy it in wildfly 10 instead of tomcat

Guest
Sissy
1 year 6 months ago

It would be a good idea, to mention how to create a xhtml-file. Should I just create a normal file with the extension .xhtml?