Viral Patel is a keen technology blogger and enthusiast. Working with a software company, he uses his leisure time to learn and explore emerging areas in tech world. His passion for technology has motivated him from creating an operating system to writing tutorials/articles on Java, JavaEE, Spring, Hibernate, Struts, jQuery, PHP. Visit the website http://viralpatel.net for a wide range of articles and tutorials on these topics. Viral has posted 13 posts at DZone. View Full User Profile

Creating JavaServer Faces Applications in Eclipse

02.23.2009
| 19736 views |
  • submit to reddit

In this article we will investigate  how to create a simple application using JavaServer Faces (JSF) framework in the  Eclipse IDE. First let us see what are the tools required to create our Hello World JSF application.

  1. JDK 1.5 above (download)
  2. Tomcat 5.x above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (download)
  3. Eclipse 3.2.x above (download)
  4. Sun Reference Implementation of JSF: (download). Following are the list of JAR files required for this application.
    • jsf-impl.jar
    • jsf-api.jar
    • jstl.jar
    • common-logging.jar
    • common-beanutils.jar
    • common-collections.jar
    • common-chain.jar
    • common-digester.jar

We will implement a JSF application with an Add User screen containing two fields, ID and User Name. Once the  user has entered these values and pressed submit, she will be redirected to a welcome page displaying the user name.

Let us start with our first JSF based web application.

Step 1: Create Dynamic Web project

Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.
dynamic web project eclipse

Select Dynamic Web application and click Next.
create dynamic web project jsf

Write the name of the project HelloWorldJSF. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. In configuration select JavaServer Faces v1.2 Project and press Next.

jsf-new-project

On Project Facets window, select Java 5 and JSF 1.2 and press Next.

Skip Web module window and press Next.

jsf-capabilities-face-servlet

Select JSF component library. Click New in Component Libraries and add jstl.jar, jsf-api.jar and jsf-impl.jar. In URL Mapping Patterns add /faces/* and then click Finish.

Once the project is created, you can see its structure in Project Explorer.
jsf-project-explorer-view

Step 2: Create Package and Managed bean

Create a package net.viralpatel.jsf.helloworld in the source folder and create a Java file UserBean.java. Copy following content into UserBean.java.

package net.viralpatel.jsf.helloworld;

public class UserBean {
	private int id;
	private String name;

	//Action method to add user
	public String addUser() {

		return "success";
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

Above is the Java class for a User bean that we will use to store our user’s information. This class acts like a form bean and action class. The addUser() method will get called when we click Add button on our Add User page.

Step 3: Create JSP files

Create two JSP files: AddUser.jsp and ListUser.jsp in WebContent folder. Copy following content in each of these files.

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

<html>
<head>
	<title>Add New User Form</title>
</head>
<body>
<f:view>
		<p>
			<h:message id="errors" for="User_ID" style="color:red"/>
		</p>
	<h:form>
		<h:panelGrid border="1" columns="2">
			<h:outputText value="ID"></h:outputText>
			<h:inputText id="User_ID" value="#{userBean.id}" required="true">
				<f:validateLongRange minimum="1" maximum="500"/>
			</h:inputText>
			<h:outputText value="Name"></h:outputText>
			<h:inputText value="#{userBean.name}"></h:inputText>
			<h:commandButton action="#{userBean.addUser}"
				value="Add Customer"></h:commandButton>
		</h:panelGrid>
	</h:form>
</f:view>
</body>
</html>

We have added a validation rule for ID using f:validateLongRange tag and required=”true” attribute. The ID must be between 1 and 500.

ListUser.jsp

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

<html>
<head>
	<title>List of Users</title>
</head>
<body>
<f:view>
	<h:form>
		<h:outputText value="User #{userBean.name} is added successfully.">
		</h:outputText>
	</h:form>
</f:view>
</body>
</html>

Step 4: Modify faces-config.xml file

Open faces-config.xml from WebContent -> WEB-INF folder and copy following content into it.

<?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>userBean</managed-bean-name>
		<managed-bean-class>
			net.viralpatel.jsf.helloworld.UserBean
		</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
	</managed-bean>
	<navigation-rule>
		<display-name>AddUser</display-name>
		<from-view-id>/AddUser.jsp</from-view-id>
		<navigation-case>
			<from-outcome>success</from-outcome>
			<to-view-id>/ListUser.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>
</faces-config>

In Faces config we have defined a managed bean UserBean with scope session and mapping from AddUser.jsp to ListUser.jsp.

Step 5: Execute and run the project

Final step is to execute the project and view it in browser.
For this, right click on Project Name in Project Explorer -> Run As -> Run on Server (Shortcut Alt+Shift+X, R).

add-new-user-jsf-project-eclipse

Once you enter ID and Username and press Add User, following success screen will appear.

add-user-success-jsf-project-eclipse

Download complete WAR file with source

Download WAR with Source (1.48 MB)

From http://viralpatel.net/blogs/

Published at DZone with permission of its author, Viral Patel.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Martijn Verburg replied on Mon, 2009/02/23 - 7:22am

I'm sure this article is seen by many as quiet basic, but for someone like me (mired in server side Java) this was a useful little article, thanks!

Chandra Lakshm... replied on Wed, 2009/02/25 - 7:12pm

thanks Dude

Saju Sam replied on Tue, 2009/03/03 - 6:22pm

hi i am getting an error SEVERE: Exception sending context initialized event to listener instance of class com.sun.faces.config.ConfigureListener java.lang.NoClassDefFoundError: javax/faces/application/ViewExpiredException at com.sun.faces.lifecycle.LifecycleImpl.(LifecycleImpl.java:79) at com.sun.faces.lifecycle.LifecycleFactoryImpl.(LifecycleFactoryImpl.java:92) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at java.lang.Class.newInstance0(Unknown Source) at java.lang.Class.newInstance(Unknown Source) at javax.faces.FactoryFinder.getImplGivenPreviousImpl(FactoryFinder.java:551) at javax.faces.FactoryFinder.getImplementationInstance(FactoryFinder.java:411) at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:229) at com.sun.faces.config.ConfigureListener.configure(ConfigureListener.java:832) at com.sun.faces.config.ConfigureListener.configure(ConfigureListener.java:502) at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:402) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4342) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardHost.start(StandardHost.java:719) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:516) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:578) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) Caused by: java.lang.ClassNotFoundException: javax.faces.application.ViewExpiredException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233) at java.lang.ClassLoader.loadClassInternal(Unknown Source) ... 29 more any help will be highly appreciated

Saju Sam replied on Tue, 2009/03/03 - 6:49pm in response to: Chandra Lakshmipathy

i am getting the following error could u pls help Mar 3, 2009 6:47:07 PM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:helloworld' did not find a matching property. Mar 3, 2009 6:47:07 PM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre6/bin/client;C:/Program Files/Java/jre6/bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\Common Files\Roxio Shared\DLLShared\;C:\Program Files\Common Files\Roxio Shared\DLLShared\;C:\Program Files\Common Files\Roxio Shared\9.0\DLLShared\;I:\_MySQL Server\bin;C:\_MySQL Server 5.1\bin; Mar 3, 2009 6:47:08 PM org.apache.coyote.http11.Http11Protocol init INFO: Initializing Coyote HTTP/1.1 on http-8080 Mar 3, 2009 6:47:08 PM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 691 ms Mar 3, 2009 6:47:08 PM org.apache.catalina.core.StandardService start INFO: Starting service Catalina Mar 3, 2009 6:47:08 PM org.apache.catalina.core.StandardEngine start INFO: Starting Servlet Engine: Apache Tomcat/6.0.18 Mar 3, 2009 6:47:08 PM com.sun.faces.config.ConfigureListener contextInitialized INFO: Initializing Sun's JavaServer Faces implementation (1.2_04-b10-p01) for context '/helloworld' Mar 3, 2009 6:47:09 PM org.apache.catalina.core.StandardContext listenerStart SEVERE: Exception sending context initialized event to listener instance of class com.sun.faces.config.ConfigureListener java.lang.NoClassDefFoundError: javax/faces/application/ViewExpiredException at com.sun.faces.lifecycle.LifecycleImpl.(LifecycleImpl.java:79) at com.sun.faces.lifecycle.LifecycleFactoryImpl.(LifecycleFactoryImpl.java:92) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at java.lang.Class.newInstance0(Unknown Source) at java.lang.Class.newInstance(Unknown Source) at javax.faces.FactoryFinder.getImplGivenPreviousImpl(FactoryFinder.java:551) at javax.faces.FactoryFinder.getImplementationInstance(FactoryFinder.java:411) at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:229) at com.sun.faces.config.ConfigureListener.configure(ConfigureListener.java:832) at com.sun.faces.config.ConfigureListener.configure(ConfigureListener.java:502) at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:402) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4342) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardHost.start(StandardHost.java:719) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:516) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:578) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) Caused by: java.lang.ClassNotFoundException: javax.faces.application.ViewExpiredException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233) at java.lang.ClassLoader.loadClassInternal(Unknown Source) ... 29 more Mar 3, 2009 6:47:09 PM org.apache.catalina.core.StandardContext start SEVERE: Error listenerStart Mar 3, 2009 6:47:09 PM org.apache.catalina.core.StandardContext start SEVERE: Context [/helloworld] startup failed due to previous errors Mar 3, 2009 6:47:09 PM org.apache.coyote.http11.Http11Protocol start INFO: Starting Coyote HTTP/1.1 on http-8080 Mar 3, 2009 6:47:09 PM org.apache.jk.common.ChannelSocket init INFO: JK: ajp13 listening on /0.0.0.0:8009 Mar 3, 2009 6:47:09 PM org.apache.jk.server.JkMain start INFO: Jk running ID=0 time=0/63 config=null Mar 3, 2009 6:47:09 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 1326 ms

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.