Main Tutorials

JSF 2.0 hello world example

In this tutorial, we will show you how to develop a JavaServer Faces (JSF) 2.0 hello world example, shows list of JSF 2.0 dependencies, basic annotations and configurations.

Project Environment

This JSF 2.0 example is built with following tools and technologies

  1. JSF 2.1.7
  2. Maven 3
  3. Eclipse 3.6
  4. JDK 1.6
  5. Tomcat 6.0.26

First, review the final project structure, in case you are confused about where should create the corresponding files or folder later.

jsf2-hello-world-example

1. JSF 2.0 Dependencies

Maven central repository has the JSF version up to 1.2 only, to get the JSF 2.0, you may need to download from Java.net repository.
The maven central repository is updated JSF library to 2.1.7. The previous Java.net repository is no longer required.

For Java EE Application Server like Glassfish
In most Java EE application servers, it has build-in support for JSF 2.0, so you need to download the single JSF API for development purpose.


...
<dependencies>
  <dependency>
    <groupId>javax.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
  </dependency>
</dependencies>
<repositories>
  <repository>
    <id>java.net.m2</id>
    <name>java.net m2 repo</name>
    <url>http://download.java.net/maven/2</url>
  </repository>
</repositories>
...

For simple servlet container like Tomcat
This is a bit troublesome, you need to download following dependencies.

File : pom.xml


<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>com.mkyong.common</groupId>
	<artifactId>JavaServerFaces</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>JavaServerFaces Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<dependencies>

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

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

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
		</dependency>
                <!-- Tomcat 6 need this -->
		<dependency>
			<groupId>com.sun.el</groupId>
			<artifactId>el-ri</artifactId>
			<version>1.0</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>JavaServerFaces</finalName>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
Note
For more detail about the JSF 2.0 dependencies, please refer to this official JSF 2.0 release note.
Warning
The el-ri.jar is an arguable dependency in the Tomcat servlet container, even it’s not stated in the release note, but you need this library to solve the “JSP version of the container is older than 2.1…” error message.

Updated – 21-10-2010
This “el-ri.jar” is too old, it’s recommended to use the latest “el-impl-2.2.jar”, from Java.net


     <dependency>
	  <groupId>org.glassfish.web</groupId>
	  <artifactId>el-impl</artifactId>
	  <version>2.2</version>
     </dependency>

Updated – 25-07-2012
This el-ri.jar dependency is no longer required in Tomcat 7.

2. JSF 2.0 Managed Bean

A Java bean or JSF managed bean, with a name property to store user data. In JSF, managed bean means this Java class or bean can be accessed from a JSF page.

In JSF 2.0, use @ManagedBean annotation to indicate this is a managed bean.
HelloBean.java


package com.mkyong.common;

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

@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private String name;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
Note
In JSF 1.x, you had to declare beans in the faces-config.xml, but this is no longer required in JSF 2.0.

3. JSF 2.0 Pages

In JSF 2.0, it’s recommended to create a JSF page in XHTML file format, a file with a .xhtml extension.

See following two JSF 2.0 pages :

Note
To use the JSF 2.0 components or features, just declared the JSF namespace at the 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">

File : hello.xhtml – Renders a JSF text box and link it with the “helloBean” (JSF managed bean), “name” property, and also a button to display the “welcome.xhtml” page when it’s clicked.


<?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>JSF 2.0 Hello World</title>
    </h:head>
    <h:body>
    	<h2>JSF 2.0 Hello World Example - hello.xhtml</h2>
    	<h:form>
    	   <h:inputText value="#{helloBean.name}"></h:inputText>
    	   <h:commandButton value="Welcome Me" action="welcome"></h:commandButton>
    	</h:form>
    </h:body>
</html>
Note
In JSF 1.x, you had to declare the “navigation rule” in “faces-config.xml“, to tell which page to display when the button is clicked. In JSF 2.0, you can put the page name directly in the button’s “action” attribute. For simple navigation, it’s more than enough, but, for complex navigation, you are still advised to use the “navigation rule” in “faces-config.xml“.

File : welcome.xhtml – Display the submitted text box value.


<?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.0 Hello World</title>
    </h:head>
    <h:body bgcolor="white">
    	<h2>JSF 2.0 Hello World Example - welcome.xhtml</h2>
    	<h2>Welcome #{helloBean.name}</h2>
    </h:body>
</html>

The #{…} indicate this is a JSF expression language, in this case, #{helloBean.name}, when the page is submitted, JSF will find the “helloBean” and set the submitted textbox value via the setName() method. When welcome.xhtml page is display, JSF will find the same session “helloBean” again and display the name property value via the getName() method.

4. JSF 2.0 Serlvet Configuration

Just like any other standard web frameworks, you are required to configure JSF stuffs in web.xml file.

File : web.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" 
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">

	<display-name>JavaServerFaces</display-name>

	<!-- Change to "Production" when you are ready to deploy -->
	<context-param>
		<param-name>javax.faces.PROJECT_STAGE</param-name>
		<param-value>Development</param-value>
	</context-param>

	<!-- Welcome page -->
	<welcome-file-list>
		<welcome-file>faces/hello.xhtml</welcome-file>
	</welcome-file-list>

	<!-- JSF mapping -->
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map these files with JSF -->
	<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>

</web-app>

Define a “javax.faces.webapp.FacesServlet” mapping, and map to those well-known JSF file extensions (/faces/*, *.jsf, *.xhtml,*.faces).

In this case, the below 4 URLs are pointing to the same hello.xhtml.

  1. http://localhost:8080/JavaServerFaces/hello.jsf
  2. http://localhost:8080/JavaServerFaces/hello.faces
  3. http://localhost:8080/JavaServerFaces/hello.xhtml
  4. http://localhost:8080/JavaServerFaces/faces/hello.jsf

In JSF 2.0 development, it’s recommended to set the “javax.faces.PROJECT_STAGE” to “Development“, it will provide many useful debugging information to let you track the bugs easily. For deployment, just change it to “Production“, you just do not want your customer to look at this annoying debugging information :).

5. Demo

A long article end with a project demo 🙂

URL : http://localhost:8080/JavaServerFaces/hello.jsf

jsf2-hello-world-example-1

A simple JSF page, with a text box and a button.

jsf2-hello-world-example-2

When the button is clicked, displays the submitted text box value.

Download Source Code

Download It (v2.1.7 example)- JSF2.0-hello-world-example-2.1.7.zip (8KB)
Download It (old v2.1.0-b03 example)- JSF-2-Hello-World-Example-2.1.0-b03.zip (8KB)

References

  1. JavaServer Faces Technology
  2. JSF 2.0 release note
  3. Wiki : JavaServer Faces
  4. Wiki : XHTML file explanation
  5. java.lang.IllegalArgumentException: javax.faces.context.ExceptionHandlerFactory
  6. JSF 2.0 + Tomcat : It appears the JSP version of the container is older than 2.1…
  7. Eclipse IDE : Unsupported content type in editor
  8. Eclipse IDE : .xhtml code assist is not working for JSF tag

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
126 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Deepak Sunanda Prabhakar
8 years ago

Hi Mkyong,

I downloaded the source code form your site but I end up getting this error when I run the project on server. I use tomcat 7.

SEVERE: Servlet /jsftutorials threw load() exception
java.lang.ClassNotFoundException: javax.faces.webapp.FacesServlet
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:527)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:509)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:137)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5033)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5317)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)

Mehmet SARIO?LU
8 years ago

It works and I think it is a good example. However I needed to find another way to add managed bean to configure faces-config.xml . Here is the link I found https://www.youtube.com/watch?v=ca38FOlgDoI

Thanks.

Jimmy
10 years ago

Hi Mkyong,
Thanks for your tutorial first. It really simple and instructive.
In this website there are lots of technologies like JSF, Spring, Struts. Some of the tutorials were made serveral years before. But technologies change a lot in even one year. Take JSF as an example, I seldom see people use it now, now more people select spring MVC. So could you please have a session on the Java Web Technology trend and the popular framework? Thanks a lot!

Sohel
3 years ago

Hi, I am getting error in mu web IDE as viewId:/hello.xhtml – View /hello.xhtml could not be restored. can any one help

Simon R
4 years ago

Thanks a lot. This helped me get up and running quickly.

ZeaLot
6 years ago

The command tags must be written within a form tag, which wasted lots of my time.

Robert
6 years ago

Good guide to get started with JSF. This was exactly what I was looking for.

????? ??????
7 years ago
Avinash
7 years ago

/hello.xhtml Not Found in ExternalContext as a Resource.

this file is under “/webapp/faces/”

Abhijit
7 years ago

can you revise topic on Tomcat 8,jdk1.8,maven,jsf 2.0 ,springframework with annotation,primefaces,eclipse mars

cleverpig
8 years ago

when I use the Mkyong’s code with jsf 2.2,just need add ConfigureListener in the web.xml:

com.sun.faces.config.ConfigureListener

Kannan
8 years ago

Please say how to build this project and how to import this project (Downloaded here) for freshers

TipTop
8 years ago

when I run with this url http://localhost:8080/JavaServerFaces/hello.jsf, it gives

<>
for other URLs it works fine.

TipTop
8 years ago

I am getting this error, how to resolve this?

2015-08-29 11:16:27.114:INFO:oejw.StandardDescriptorProcessor:main: NO JSP Support for /JavaServerFaces, did not find org.eclipse.jetty.jsp.JettyJspServlet
2015-08-29 11:16:27.173:WARN:oejs.BaseHolder:main:
java.lang.ClassNotFoundException: javax.faces.webapp.FacesServlet
at java.net.URLClassLoader.findClass(Unknown Source)
at org.eclipse.jetty.webapp.WebAppClassLoader.findClass(WebAppClassLoader.java:510)

Jai krishna
8 years ago

These examples are very useful and to get a quick dip into these java aspects. Thank you

ke ja
8 years ago

Mkyong, Would you please consider my question below?

ke ja
8 years ago

How can I display version and date of build in the xhtml page read from manifest in run time?

Khan
9 years ago

Nice Example mkyoung man u r great Your tutorial works good

Larry K.
9 years ago

Thank you very much

ved
9 years ago

I am getting this error:

javax.el.PropertyNotFoundException: /hello.xhtml @14,48 value=”#{HelloBean.name}”: Target Unreachable, identifier ‘HelloBean’ resolved to null

SOLVED IT by :
org.apache.myfaces.annotation.SCAN_PACKAGES
com.veke.hello

Israel Altamira
3 years ago
Reply to  ved

thank you!!
found same issue working with jetty eclipse plugin (Run Jetty Run) (jetty vr 6.1.26).

Additionally had to add some changes like suggested in next link (add
https://stackoverflow.com/questions/21673480/maven-jsf-2-0-doesnt-work-on-embedded-tomcat)

  1. remove Mojarra dependecies in my POM
  2. add MyFaces dependecies in my POM:

<dependency>
  <groupId>org.apache.myfaces.core</groupId>
  <artifactId>myfaces-api</artifactId>
  <version>2.2.0</version>
  <scope>compile</scope>
</dependency>

<dependency>
  <groupId>org.apache.myfaces.core</groupId>
  <artifactId>myfaces-impl</artifactId>
  <version>2.2.0</version>
  <scope>compile</scope>
</dependency>

3. change listener-class on my web.xml

<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>

4. add context-param on my web.xml

<context-param>
   <description>Defines which packages to scan for beans, separated by commas. Useful for when using maven and jetty:run (version 6) or tomcat:run
  </description>
  <param-name>org.apache.myfaces.annotation.SCAN_PACKAGES</param-name>
  <param-value>com.company.demo</param-value>

Jason Wee
5 years ago
Reply to  ved

use tomcat9 with jdk 12 and web.xml using 3.0 servlet spec, should work, cause i tested it.

vick
5 years ago
Reply to  ved

old, but what do you mean with org.apache.myfaces.annotation.SCAN_PACKAGES
com.veke.hello?

Christian Maíz
9 years ago

excellent tutorial, but I would like to correct a point about the servlet url-pattern,
in the case of /faces/* it just work with the same extension of the source code file extension, and not with the other url-pattern extension you set (*.jsf, *.faces), so the 4th url won’t work

vadin
9 years ago

no its working for me

????? ??????
7 years ago
Reply to  vadin
vadin
9 years ago

good

Aditi
9 years ago

I am a beginner of Java and have designed few pages in html where I wrote code in notepad and saved it as .html and then ran. For xml or xhtml or JSF where do I write code and run it?

sath
9 years ago
Reply to  Aditi

You should have an application server like apache tomcat to run it. You can use a IDE like eclipse and create a dynamic web project . Then export it as a war file . then deploy in apache tomcat web apps folder. start the server and access the site localhost/yourapp

Felix
9 years ago

Does Apache Tomcat 8 have already support JSF 2.0 I expect?

The White Engineer
9 years ago

How i can run the project in Eclipse

Aditya
9 years ago

How does JSF know there is a ‘helloBean’ in the above example ‘welcome.xhtml’?
can i use something like this #{myBean.name} instead of #{helloBean.name}?

gulam
10 years ago

I am doing hello JSF 2.2 ==============

web.xml file is :

helloJSF

index.jsf

Faces Servlet

javax.faces.webapp.FacesServlet

1

Faces Servlet

*.jsf

—————————————–

http://localhost:8080/hello —————————— NO works***

@http://localhost:8080/hello/index.jsf ————- it works fine

samir
10 years ago

The example was really helpful. I am richfaces 4. would you be knowing how to enable the content assist for richfaces tag in eclipse?

gani
10 years ago

in the 4URLs…… the fourth-one must be

http://localhost:8080/JavaServerFaces/faces/hello.xhtml== ite not “………./faces/hello.jsf”