In this JSF tutorial and example, we will write a simple Hello World example using JSF and it’s default renderer – HTML renderer on Eclipse IDE. Next, the application will be deployed on tomcat, and run to see results.  Functionality of our project is simple – enter first name and last name, on press of submit button, show the complete name. If any field is empty then show error.

Create a Dynamic Web Project

Create dynamic web project in eclipse using following steps. In eclipse, click on New > Project to arrive at following screen.

JSF Tutorial

On this screen, select Dynamic Web Project and press next button.

Create Dynamic Web Project Step 2

In this screen enter the Project name, and select the directory where you want the code to be stored. It can be in your default workspace. Press next button.

Create Dynamic Web Project Step 3

Here, change the Java source directory to ‘srcmainjava’, good to have main and test java resources separated. Click on finish button and the dynamic web project will be created.
Last thing, right click on project and go to properties > Java Build Path > Source Tab. Change the default output folder to ‘JSFTutorial/WebContent/WEB-INF/classes’.

Set Default Output

Add Required Libraries:

Add following jar files to the project. The Jsf jars can be downloaded from JSF project site. Dependencies can be downloaded from Maven central repository.

WebContent/WEB-INF/lib

commons-beanutils.jar
commons-chain.jar
commons-collections.jar
commons-digester.jar
commons-logging.jar
jsf-api.jar
jsf-impl.jar
jstl.jar

Ensure compatibility in amongst the jars.

Create JSP

Add this jsp to the document root. This is the first jsp we call to start our Hello World application.

/WebContent/HelloWorld.jsp

<%@taglib 
uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>
<head><title>Hello World</title></head>
<body>
<f:view>
		<p>
			<h:message id="errors" for="firstName" style="color:red"/>
			<h:message id="errors1" for="lastName" style="color:red"/>
		</p>
	<h:form>
			<h:outputText value="First Name"></h:outputText>
			<h:inputText id="firstName" value="#{helloWorldBean.firstName}" 
			required="true">
			</h:inputText>
			<h:outputText value="Last Name"></h:outputText>
			<h:inputText id="lastName" value="#{helloWorldBean.lastName}" 
			required="true"></h:inputText>
			<h:commandButton action="#{helloWorldBean.sayHelloWorld}"
				value="Get Complete Name"></h:commandButton>
	</h:form>
</f:view>
</body>
</html>

Below are the highlights of this jsp.

  • Jsf core and html tag libraries are used.
  • Root component is core library view tag (f:view).
  • Error messages are displayed using html message (h:message) tags in red color formatting.
  • All components to be submitted through request are included in html form tag (h:form).
  • All components are linked with HelloWorldBean.
  • ‘firstName’ and ‘lastName’ are required fields and use validation provided by jsf.
  • Command Button is linked with a method sayHelloWorld() in HelloWorldBean.

Next, we have the jsp which will result after submission of above jsp. This jsp shows the result of submission i.e. complete name.
/WebContent/HelloWorldResult.jsp

<%@taglib uri="http://java.sun.com/jsf/core" 
prefix="f"%> <%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>
<head><title>Hello World Result</title></head>
<body>
<f:view>
	<h:form>
		<h:outputText value="Complete Name is 
		#{helloWorldBean.completeName}">
		</h:outputText>
	</h:form>
</f:view>
</body>
</html>

Create Backing Bean

We use following POJO as a backing bean for the jsps. This has attributes for our functionality with getter and setter methods. In addition to this, it has a method ‘sayHelloWorld’ that handles the submit button action.
/src/main/java/com/myhomepageindia/jsftutorial/web/bean/HelloWorldBean.java

package com.myhomepageindia.jsftutorial.web.bean;

public class HelloWorldBean {
	private String firstName;
	private String lastName;
	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 getCompleteName() {
		return this.firstName + " " + this.lastName;
	}
	public String sayHelloWorld(){
		return "success";
	}

}

Create Configuration File

Jsf looks for faces-config.xml in classpath and loads the configuration defined from here. Here we have defined managed bean (the backing bean), and navigation rule that takes to second jsp on submission from first jsp.

/WebContent/WEB-INF/faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>  

<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
    version="1.2">
    <managed-bean>
        <managed-bean-name>helloWorldBean</managed-bean-name>
        <managed-bean-class>
            com.myhomepageindia.jsftutorial.web.bean.HelloWorldBean
        </managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <display-name>HelloWorld</display-name>
        <from-view-id>/HelloWorld.jsp</from-view-id>
        <navigation-case>
            <from-outcome>success</from-outcome>
            <to-view-id>/HelloWorldResult.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
</faces-config>

Modify Web.xml

We modify the web.xml to define the main servlet i.e. FacesServlet. Also notice the url pattern configured to include ‘jsf’ word.

WebContent/WEB-INF/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>JSFTutorial</display-name>
  	<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>/jsf/*</url-pattern>
	</servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Now our application is ready to run. Build the application. Deploy it on server by right clicking on project and selecting ‘Run on Server’.

Run on Server

Next call the HelloWorld.jsp as shown below. Using url http://localhost:8080/JSFTutorial/jsf/HelloWorld.jsp. The page will be displayed as shown below.

JSF Tutorial

Enter values and press the button to get the results. That’s it, hello world of our JSF Tutorial is working.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS