JSF hello world example in eclipse

Let us start JSF programming with simple hello world example.

Example explanation:

Create a managed bean class “HelloWorld.java” which is used for interacting with User Interface and business logic. HelloWorld.java contains the getter method of message property. Register the managed bean class into faces-config.xml and provide the details like name and scope etc. Insert the JSF controller servlet “FacesServlet” entry into web.xml. Create a jsf page “helloworld.xhtml”. When “helloworld.xhtml” renders it use managed bean class name defined in faces-config.xml file to access its property. The managedBeanName.mangedBeanProperty expression calls the getter method of the mangedBeanProperty so in our example helloWorld.message calls the getter of message property in HelloWorld.java.

Example:

HelloWorld.java
package com.javawithease.business;
 
/**
* Managed bean.
* @author javawithease
*/

public class HelloWorld {
public String getMessage() {
return "JSF hello world example.";
}
}
faces-config.xml
<?xml version="1.0" encoding="windows-1252"?>
<faces-config version="2.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xi="http://www.w3.org/2001/XInclude"
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_2_0.xsd"
>
 
 
<managed-bean>
<managed-bean-name>
helloWorld
</managed-bean-name>
<managed-bean-class>
com.javawithease.business.HelloWorld
</managed-bean-class>
<managed-bean-scope>
session
</managed-bean-scope>
</managed-bean>
 
</faces-config>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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-app_3_0.xsd"
>
 
<servlet>
<servlet-name>faces</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
 
<servlet-mapping>
<servlet-name>faces</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
 
</web-app>
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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>JSF hello world example.</title>
</h:head>
<h:body>
<h3><h:outputText value="${helloWorld.message}"/></h3>
</h:body>
 
</html>

URL:

http://localhost:7001/JSFExample1/faces/helloworld.xhtml

Output:


 

No comments: