Category Archives: JSF

Is JSF Dying?

We remember the hype that rocked java world with entry of this web tier framework. It is different as compared to those frameworks which (actually) are front runners of web application technology stack. These include Struts, Spring MVC, Tapestry and many more. These frameworks provided simple MVC based web tier, and a set of classes abstracting the non functional part. This definitely made us to leave behind the MVC implementation of Jsp – Servlet – POJO/EJB, and use these frameworks instead. These technologies varied more in richness than fundamentals. Arrival of Java Server Faces (JSF) triggered a different thinking line. Reusable components and event based programming buzzed around us.

Java Server Faces (JSF) Tutorial

JSF – Java Server Faces is a web tier technology. This technology is different from other JEE web tier technologies in many aspects. This tutorial helps you to understand building blocks of JSF, compares it with other web tier technologies like Struts, Spring MVC etc. Following detailed articles constitute this tutorial.

JSF Hello World Example on Eclipse and Tomcat: An example code that can be a starting point for your trials of JSF technology.

Mapping JSF with Other Web Tier Technologies: This article explores similarities, and differences amongst JSF and other web tier frameworks.

Applying Java Server Faces Technology (JSF) to JSP: In this article, we find out the changes that we have to make to user jsp with JSF.

JSF Request Handling Life Cycle: Here we discuss the two scenarios of JSF request handling cycles.

JSF Request Handling Lifecycle

By now you must have understood what is jsf, how to write simple application using jsf, and what are the changes required if you want to use jsp with jsf. In this article, we will try to explore the request processing by jsf. How does it work when we submit a request from client browser?

We need to consider two scenarios here. These scenarios arise because JSF handles first page request from client differently than a post back request(repeat request for same page).

Request Processing for First Request:

The JSF request for a page can be to display an empty page in which a user will enter data. Here, we may not have any event getting fired to retrieve data and plug it in the components. Second important difference is that the view to be rendered, needs to be created for first use. Following diagram explains how all this works.

Handling First Request

  • Create View: Based on requested page, a view is created by constructing a tree of components used in the jsp.
  • Store View in FacesContext: View created in above step is set in FacesContext object so that it can be taken through next stages.
  • Render Response: Nothing else is needed, hence the view is rendered using configured or default HTML renderer.

 Request Processing for Post-back Requests:

This is the second scenario, here the request is sent for a page which has an existing generated view. Here the request contains data entered by user and submitted back to the server. Now the life cycle will need few additional steps to handle this data. Let us see the additional stages we need in above diagram.

Handling Postback Requests

  • Restore View: Taking view id from the input request, in this phase, the FacesServlet retrieves the view (stored at client or server side). This restored view is available for next processing stages.
  • Apply Request Values: Values submitted from client side (mostly user entered values) are converted to required format, and these values are applied to the components in restored view.
  • Process Validations: View components with converted values are input to this stage. In this stage, validations are applied to the values. (Mind you the conversion related validations are already done in Apply Request Values stage.)
  • Update Model Values: Validated values are available in view components as a input to this stage. Further these values are ready to go into the backing beans. This stage sets the values in backing bean by calling appropriate setter method.
  • Invoke Application: This stage invokes action/action listener to get the business processing done.
  • Render Response: Same as first request, in this stage the response is rendered to client using configured or default renderer.

Applying Java Server Faces (JSF) Technology to Jsp

Normally, a jsp contains static and dynamic contents. Static contents are written using html while dynamic contents are executed at server side, and the resultant data is presented again in html format. When a page is presented in a browser, it contains sequence of html tags that are nested to present view elements and data. When we are working with JSF, the presented page is still the same, but the way jsp code is written, and the way it is processed by the container, there is major difference. Let us see what we have in Jsf.

Logical Description of Jsp Compoents:

  • Everything is a component. Text fields, tables, rows, columns, hyperlinks, buttons, forms etc. are components. All these components are encapsulated in view component. Also, these components can be nested.
  • Some of the components can be liked to backing bean (POJO) attributes.
  • Each component is eligible for few events. The events can be value change events e.g. in case of text box, we enter something, or action events e.g. button press. Applicable events can be attached to the components.
  • Some of the components will require certain validation. Validators performing such validations can also be attached to the components.
  • Values entered by user will require conversion to a data type of liked backing bean attribute. Such convertors can also be defined for components.
  • Finally, all above components, validators, convertors and components are readily available with JSF framework (mainly in the form of custom tags). If you require anything different, then there is facility to write your own custom elements also.

In next section, let us actually see implementation details of above components.

Implementation Details of Jsp Components:

In this section, we are not going in details of each component. Detail documentation is available in Jsf tag library reference. Here we extract a quick reference for all important components, which mostly we need when we write a Jsp with Jsf framework.

  • Custom Tag Declaration: Jsf provides to core tag library, which is independent of any rendering toolkit. In addition to that, it also provides html tag library, which is actually html rendering kit. If we are using html renderer provided by Jsf then we need to import both the libraries here. We can also opt to use JSTL tag library instead and get rid of these. But this means we don’t want to use component based request handling of Jsf. Add following declaration to the jsp. Wherever applicable, we are going to refer to this declaration prefixs.

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

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

  • View Tag: Each component we include in our jsp should be enclosed in this view tag. This is the base for everything that is presented on browser. It is also required to enclose all Jsf component tags inside a view tag.

<f:view>

………..

………..

</f:view>

  • Form Tag: Everything that needs to be submitted to the server will be enclosed inside form tag. This tag we are going to use from the html tag library.

<h:form>

………..

………..

</h:form> 

  • UIInput Tags: As the name means, these tags handle the data (mostly user entered data) submission to the FacesServlet. These tags belong to html tag library. There are four possible renderers to these tags – Hidden, Secret, Text and Text Area. We can attach validators and convertors to these components only. Following UIInput component tags are available in Jsf.
    • inputHidden – Renders hidden text
    • inputSecret – Renders password fields
    • inputText – Renders text box.
    • inputTextarea – Renders text area field

<h:inputText id=“firstName”></h:inputText>

  • UIOutput Tags: These html tags are used to render data out. Label, link, outputmessage and text are the renderers available with this tag. Following UIOutput component tags are available.
  • o outputLabel – Renders label
  • o outputLink – Renders a link
  • o outputFormat – Renders message
  • o outputText – Renders output text

<h:outputText value=“First Name”></h:outputText>

  • Linking with Backing Bean: Backing bean is a POJO, which can be used for two purposes. First to link the UIInput tag values to the attributes of it (POJO/backing bean). Second is linking actions to the methods doing processing and returning result.

<h:inputText id=“firstName” value=”#{helloWorldBean.firstName}” required=“true”>

</h:inputText>

<h:commandButton action=”#{helloWorldBean.sayHelloWorld}”

                        value=“Get Complete Name”></h:commandButton>

  • Validators: Validators can be the validators provided by Jsf or we can also build custom validators. These validators are attached to the components that get data input i.e. UIInputs.

<h:inputText id=“firstName” value=”#{helloWorldBean.firstName}” required=“true”></h:inputText>

  • Convertors: Convertors convert the values submitted from client to a data type required by the mapping backing bean attribute. Jsf provides a set of standard convertors. We can also write a custom convertor and attach it to a component derived from UIInput.

<h:inputText id=“id” value=”#{helloWorldBean.id}” required=“true” converter=”javax.faces.convert.IntegerConverter>

                  </h:inputText>

 

  • Displaying Messages: This is another concern a developer needs to handle, display error messages in appropriate language and format. Language concern is explained below. Jsf html tag library has message tag that can be used to render a message. Style attribute of this message is to format the message.

      <h:message id=“errors” for=“firstName” style=“color:red”/>

 

  • Localization: Localization is presenting information in the language of user. Business data localization is to be implemented programmatically through backing beans, but Jsf provides ability to localize the static contents i.e. labels, messages etc. in desired language. Localization can be achieved in two steps.
    • Including resource bundle in desired language.

<f:loadBundle var=”bundle_en”

basename=”messages.CustomerMessages” />

  • ?
    • Using resource bundle contents.

<h:outputText value=”#{bundle_in.firstName}”/>

 

  • Additional Tags: Following additional tags are used for specific component rendering.
    • UIPanel: It provides container to group multiple components.
    • dataTable: Used for data bound tables.
    • graphicImage: Used to render images.
    • selectBooleanCheckbox: Radio button in different formats
    • selectManyCheckbox: Multiple value selection
    • UISelectXXXXX: Select (option/combo box) components having UISelectItem, UISelectItems and UISelectItemGroup components.

Backing Beans:

Similar to Struts and Spring MVC framework, these backing beans are actually Plain Old Java Objects (POJOs). Attributes of these Java classes are liked with components to transfer data between client and server. Other operations can be linked to submit actions on pages. FacesServlet does the job of population of these objects, from the component values and vice versa. It also executes the backing bean method mapped to an action.

Summary:

Jsf does use the Jsp technology to build a view, but now everything is a reusable component with different execution lifecycle.

 

JSF Hello World Example on Eclipse and Tomcat

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.

Powered by WordPress | Designed by: seo service | Thanks to seo company, web designers and internet marketing company