JSF Hello World Example on Eclipse and Tomcat - JEE
Home » JEE, JSF, Tech Notes

JSF Hello World Example on Eclipse and Tomcat

4 May 2009 13 Comments

In this example, we will write a simple application 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.
Create Dynamic Web Project Step 1
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.

Call Hello World

Enter values and press the button to get the results.

 

More Related Posts in JEE, JSF, Tech Notes

13 Comments »

  • amresh said:

    thanks

  • Sathia Kumar Subaramanian said:

    Very Nice and Very Useful for Technologies Carrier

  • Arvind said:

    in web.xml u din’t change welcome file
    how it will work?

    i am trying but i am not able to run same program

  • Abdullah İlhanlı said:

    Good example starter project thanks in advance

  • Dennis said:

    Thanks for sharing

  • octavian said:

    This is the best example for beginners. Thank you very much .

  • Dheeraj said:

    I am using eclipse 3.4.1.
    tomcat 6.0

    when i am running my code i am getting following error

    type Exception report

    message

    description The server encountered an internal error () that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: /HelloWorld.jsp(14,14) ‘#{HelloWorldBean.firstName}’ Target Unreachable, identifier ‘HelloWorldBean’ resolved to null
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:256)

    root cause

    org.apache.jasper.el.JspPropertyNotFoundException: /HelloWorld.jsp(14,14) ‘#{HelloWorldBean.firstName}’ Target Unreachable, identifier ‘HelloWorldBean’ resolved to null
    org.apache.jasper.el.JspValueExpression.getType(JspValueExpression.java:61)
    com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:81)
    javax.faces.component.UIInput.getConvertedValue(UIInput.java:934)
    javax.faces.component.UIInput.validate(UIInput.java:860)
    javax.faces.component.UIInput.executeValidate(UIInput.java:1065)
    javax.faces.component.UIInput.processValidators(UIInput.java:666)
    javax.faces.component.UIForm.processValidators(UIForm.java:229)
    javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1030)
    javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:662)
    com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:100)
    com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251)
    com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:244)

    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.30 logs.

  • sanjay said:

    Its very simple and good example,
    Thanks,
    Sanjay

  • bibi said:

    I am getting next error:
    Can not find the tag library descriptor for “http://java.sun.com/jsf/core”, even if I added the mentioned libraries.

  • Matt said:

    thanks and i expect more and more examples of JSF….excellent job…Go ahead…wish u all the best…

  • Sergei said:

    Thanks a lot for your tutorial, it helped me to understand JSF technology!

  • Sergei said:

    Thanks a lot for your tutorial, it helped me to understand JSF technology!!!

  • santosh said:

    thanks,its really very useful.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.