Java Server Faces or JSF for short is another new exciting technology for developing web applications based on Java technologies. This JSF Introductionsection introduces you with cool JSF technology. In this "JSF Introduction" section you will be introduced with the JSF technology, reasons that initiated the development of JSF and the benefits of JSF.
Why JSF?
Let's first understand the reasons that initiated the JSF project and why JSF is so hot these days. There are reasons for development of new framework in-spite of many already existing technologies like JSP, Servlets, Struts etc... If you have developed complex web based applications in jsp then you must be knowing the problem faced with those technologies. Here are the list of some of the problems faced with the previous technologies like JSP and Servlets:
- Tedious and repetitive coding
Previous technologies like JSP make programmer to do a lot of tedious and repetitive coding.
- Directly working with HTTP request and response
Using these technologies programmers directly work with HTTP request and response objects and manipulates the data. For example if user submits the registration form then programmer writes the code to get the values of each element in the form into a variable for further processing. When there is a need to retrieve the data from database and then show on the form for editing, then in this case programmer writes the code to retrieve the code from database and then set the values in the forms.
- Non availability of IDE
Non availability of IDE is another major drawback which affects the programmers productivity and development cost of the projects increases.
JSF changes all that by giving intuitive framework to the developers. Furthermore, JSP is specification and many vendors are developing their own implementations. Both free and commercial implementations of JSF are available these days. You can choose any one of them based on your requirement and budget.
Now a days software vendors are developing IDE for developing JSF based applications which is another good news for the learners of JSF framework. Once you are familiar with the core concepts of the JSF you can kick start the development of software projects using any IDE available in the market. These changes in the programming world makes the life of programmer much easier.
Java Server Faces is a component oriented and event driven framework for web applications. JSF eases the development of GUI for web applications. JSF allows the programmers to work with extensible user interfaces like buttons, text boxes, check boxes etc... Programmer writes the code for particular event such as button clicked. This makes programming much easier and now the there is no need to write request and response processing logic.
JSF was developed by Java Community Process(JCP). This is a community of web application experts. These experts are from different groups like Jakarta Struts, Oracle, Sun, IBM, ATG etc. They all collectively worked together to take the best from existing technologies and removed problems. So their collective effort brought a new technology named Java Server Faces (JSF).
Java Server Faces or JSF for short, is the standard framework to simplify the process of developing web application in java. It is a robust component framework, event driven programming model. It offers a set of UI components, extensible architecture, supports multiple client devices etc. Extensible means additional functionality can be given on the top of JSF core i.e. we can customize the functionality. JSF is vendor independent technology that is a standard to be supported by whole software industry.
One of the main feature of JSF is that it has not only been designed for coding experts but for others also like :
- Page authors
Web designers have experience with graphic design. They can design look and feel of web application in html/jsp using custom tag libraries of JSF.
- Application developers
Application developers can integrate this design with UI components. They program objects, event handles, converters, validators.
- Component writers
Component developer can build custom UI components because of JSF’s extensible and customizable nature. They can create their own components directly from UI component classes or extending the standard components of JSF.
- Application architects
Application architects are responsible for designing web applications. Defining page navigation, ensuring Scalability of application, configuring beans object registration are the key points that an application architect handles.
- Tool vendors
JSF is well suited for tool vendors, for example Sun Java Studio Creator application development tool, who provide tools that take advantages of JSF to create UI easier.
In the past many web development frameworks came in to existence founded on servlet and jsp. Struts emerged as a standard web application framework. It became framework of choice because it came early in the market and provided necessary features at the time but competitors continued providing additional features that struts lacks. So it became necessary for java to advent new standard framework with a powerful component model. This was the reason for developing JSF technology. So main purpose of developing JSF was to create a collection of APIs for the UI components with the capacity to manage their states, handle events and validation.
Struts has an option to migrate to JSF. The simplest option is to use JSF components and rest as usual. This will enable them to take advantage of third party JSF components. Main feature of JSF is ease of use. Developing web applications is easier and faster than other frameworks like struts because JSF supports UI components and easy event handling. Taking advantages of third party components can reduce the cost of rewriting existing elements, minimize the time of development.
Struts has an option to migrate to JSF. The simplest option is to use JSF components and rest as usual. This will enable them to take advantage of third party JSF components. Main feature of JSF is ease of use. Developing web applications is easier and faster than other frameworks like struts because JSF supports UI components and easy event handling. Taking advantages of third party components can reduce the cost of rewriting existing elements, minimize the time of development.
JSF is new standard framework, developed through Java Community Process (JCP), that makes it easy to build user interfaces for java web applications by assembling reusable components in a page. You can think of JSF framework as a toolbox that is full of ready to use components where you can quickly and easily add and reuse these components many times in a page and capture events generated by actions on these components. So JSF applications are event driven. You typically embed components in a jsp page using custom tags defined by JSF technology and use the framework to handle navigation from one page to another. Components can be nested within another component , for example, input box, button in a form.
JSF is based on well established Model-View-Controller (MVC) design pattern. Applications developed using JSF frameworks are well designed and easy to maintain then any other applications developed in JSP and Servlets.
JSF eases the development of web applications based on Java technologies. Here are some of benefits of using JSF:
- JSF provides standard, reusable components for creating user interfaces for web applications.
- JSF provides many tag libraries for accessing and manipulating the components.
- It automatically saves the form data and repopulates the form when it is displayed at client side.
- JSF encapsulates the event handling and component rendering logic from programmers, programmers just use the custom components.
- JSF is a specification and vendors can develop the implementations for JSF.
- There are many GUIs available these days to simplify the development of web based application based on JSF framework.
JSF Components
JSF includes mainly:
- Set of APIs to represent and manage state of components that helps server side validation, event handling, page navigation, data conversion etc.
- JSP custom tag library to create UI components in a view page.
The UI (user interface) created using JSF technology runs on server and output is shown to the client. Goal of JSF is to create web applications faster and easier. Developers can focus on UI components, events handling, backing beans and their interactions rather than request, response and markup. JSF hides complexities to enable developers to focus on their own specific work.
JSF Versions
JSF started its journey from version 1.0 and now it has come to the latest version of JSF is 1.2. The listing of versions released so far are :
- JSF 1.2 (11 may 2006) - Latest release of JSF specification.
- JSF 1.1 (27 may 2004) - Bug fix release. No specification changes. No HTML renderkit changes.
- JSF 1.0 (11 mar 2004) - Initial releaseof JSF specification.
There are many releases of 1.1 and 1.2 and these are listed below showing released date also:
- 1.2_04 P01 (20 Mar 2007)
- 1.2_04 (5 Mar 2007)
- 1.2_02 (25 Aug 2006)
- 1.2_01 (14 July 2006)
- 1.1_02 (24 Apr 2006)
- 1.1_01 (07 Sep 2004)
The JSF specification was developed under the Java Community Process (JCP) as JSR 127, which released JSF 1.0 and 1.1, and JSR 252 which released JSF 1.2. The first release of JSF is JSF 1.0 in 2004. JSF 1.0 supports servlet 2.3 and jsp 1.2. After JSF 1.0, JSF 1.1 was released. The main purpose of this release was bug-fixing. There were no specification or HTML renderkit changes. This version also works with same version of servlet 2.3 and jsp 1.2 as in the case of JSF 1.0.
JSF 1.1_01 release features bug fixes and performance improvements. Improvements include compression of views serialized to the client, failover support when storing views on the server, renderer fixes, and several other bug fixes and enhancements.It supports JDK 1.3.1 or later. Many bugs have been fixed so if your application depends on one of these bugs, it needs to be changed.
JSF 1.2 is the latest release and it works with servlet 2.5 and jsp 2.1. If you want to run JSF 1.2 on Tomcat, you want 6.0 not 5.5. So JSF needs a web container that supports atleast servlet 2.3 and jsp 1.2 and these are part of J2EE 1.3.
New in JSF 1.2
In this section we will go through some new features and changes in JSF 1.2 specification. JSF 1.1 was designed for JSP 1.2 and so could not take advantage of newer JSP features and JSP could not be changed to fill the needs of JSF. This resulted in a number of new features and changes. For ex.
- Unified Expression Language(EL) :
Unified EL has been added to JSTL to overcome problems when integrating JSP EL with the JSF EL.EL was used to access data objects in a simple way. It is used mainly as a short-hand for accessing values. Later it was included in JSP 2.0 with more functionality.When JSF was released it also needed EL.JSF and JSP each has its own EL.The JSP EL is much flexibile to the web application developer but JSF people were unsatisfied by the JSP EL.One of the reason was that it requires JSP engine to evaluate expression at the appropriate time during the lifecycle, but JSP expressions are evaluated immediately. The second reason behind it was that JSP functions could only call static methods in TLD and they cannot be used to invoke public methods dynamically on server side objects during lifecycle to validate data and handle component evevts.
So these were the reasons for developing such an EL that would work for both JSP and JSF and make using JSP and JSF together easier. This new EL is called unified EL. So this was inspired by EL used in JSTL and JSP. There is a package "el" in javax package that represents EL.
In addition to the features already available in the JSP EL, unified EL has the following features :
1. Deferred evaluation of expressions i.e.evaluation of the expression at the appropriate time during the page lifecycle from JSP engine.
2. Support for expressions that can set and get values
3. Support for expressions that can invoke methods.
4. A pluggable API for resolving expressions - Ajax Support :JSF framework can make things a little easier to write AJAXian JSF components.JSF allows to map different instances of the FacesServlet with different lifecycles.For example, one mapping for standard JSF requests and another for AJAX JSF requests.
- New Tree Creation and Content Interweaving Model for Faces applications that use JSP :We can make JSF application without using any JSP page but it can also be developed using both JSP and JSF.Using JSP makes some developers easy to handle.Sometimes When integrated it did not respond as we expect. These problems have been resolved in JSF 1.2.There have been made some changes in specification of the implementation of the FacesViewHandler for JSP and JSP custom tag base class.
- Integration with JSTL :Using JSTL's <c:forEach> tag to contain Faces input components was one of the problem, because JSP has no notion of a postback, it was not possible to apply the values correctly to the nested input components on postback. Some new concepts in EL make it possible to use this tag fully with any kind of JSF component.
- Back Button issues and Multi Frame or Multi Window Faces Apps :JSF have fixed the problem related to Multi Frame or Multi Window applications.The browser back button also created some problems. These problems were because of deficiency in the State Management API.
- Associating a message with a particular component in the page :Previously we could not include label of a component dynamically in an error message for that component. Now it's possible in new JSF 1.2.It's also possible to override the conversion or validation message that is displayed to the user on a per-instance basis.
- Expose an application wide ResourceBundle to the EL :<resource-bundle> element in faces-config allows listing many resource bundles that should be exposed to the EL using the new ELResolver chain.This optimize performance and prevent the need to create a ResourceBundle for every request.
- Use of multiple renderKits.
- Provide XML Schema for the config files, instead of using DTD.
- Security enhancements for client side state saving.
- Solve the "duplicate button press" problem.
- The portlet related bug-fixes.
JSP 2.1 is developed under JSR-245 and JSF 1.2 is developed under JSR-252. These two groups have experts and they are working independently but the main focus of development was to provide more support and compatibility between these two technology that are powerful web presentation technology so that they can be useful for each other.
JSF Features
JSF is a rich featured framework of JAVA technology. JSF provides a set of standard features that makes it a powerful and standard among the existing technologies available for the development of web application based on java technologies. Some of the features have been given below to justify the above statement.
- JSF is standard web user interface framework for Java.
- Built on top of Servlet API.
- JSF is a component framework
- UI components are stored on the server.
- Easy use of third party components.
- Event driven programming model.
- Events generated by user are handled on the server.
- Navigation handling.
- Can automatically synchronize UI components .
- JSF supports multiple client devices.
- JSF has extensible architecture.
- International language support.
- Extensive tool support (Sun, Oracle , IBM etc.).
- Rapid application development approach.
A short view of jsf features has been given above. Its main features are component model, event driven, extensible architecture, rapid application development. All of the features will be described in subsequent topics.
JSF best suits in to the java web development environment because of reasons described below : JSF has many advantages over other existing frameworks that makes it a better choice for web application development. Some of the reasons are below:
Easy creation of UI:It makes easier to create complex UI for an applicaton using jsf tags.Its APIs are layered directly on top of servlet APIs that enables us to use presentation technology other than JSP,creating your own custom components and rendering output for various client devices.
Capacity to handle complexities of UI management: It handles cleanly the complexities of UI management like input validation, component-state management, page navigation, and event handling.
Clean separation between presentation and logic:One of the greatest advantage of jsf is to clearly separate behaviour and presentation in an application. JSF is based on the Model View Controller (MVC) architecture.
Shorter development cycle:This separation between logic and presentation enables a wide range of users( from web-page designers to component developers). It allows members of team to focus on their own work only , resulting in division of labour and shorter development cycle.
Standard Java framework:JSF is a Java standard which is being developed through Java Community Process (JCP). Several prominent tool vendors are members of the group and are committed to provide easy to use, visual, and productive develop environments for JavaServer Faces.
An extensible architecture:
JSF architecture has been designed to be extensible.Extensible means additional functionality can be given on the top of JSF core i.e. we can customize the functionality. JSF UI components are customizable and reusable elements. You can extend standard components and create your own complex components like stylish calendar, menu bar etc.
Support for multiple client devices:Component developers can extend the component classes to generate their own component tag libraries to support specific client. JSF flexible and extensible architecture allows developers to do so.
Flexible rendering model:Renderer separates the functionality and view of the component. So we can create multiple renderers and give them different functionality to get different appearance of the same component for the same client or different .
International language support: Java has excellent support for internationalization . It allows you to localize messages with user specific locale. A locale is a combination of a country, a language, and a variant code. JavaServer Faces adopts this property and let you specify which locale your application supports. So you can display you messages in different languages.
Robust tool support:There are several standard tool vendors like Sun Java Studio Creator who provide robust tools that take advantages of JSF to create server side UI easily.
Easy creation of UI:It makes easier to create complex UI for an applicaton using jsf tags.Its APIs are layered directly on top of servlet APIs that enables us to use presentation technology other than JSP,creating your own custom components and rendering output for various client devices.
Capacity to handle complexities of UI management: It handles cleanly the complexities of UI management like input validation, component-state management, page navigation, and event handling.
Clean separation between presentation and logic:One of the greatest advantage of jsf is to clearly separate behaviour and presentation in an application. JSF is based on the Model View Controller (MVC) architecture.
Shorter development cycle:This separation between logic and presentation enables a wide range of users( from web-page designers to component developers). It allows members of team to focus on their own work only , resulting in division of labour and shorter development cycle.
Standard Java framework:JSF is a Java standard which is being developed through Java Community Process (JCP). Several prominent tool vendors are members of the group and are committed to provide easy to use, visual, and productive develop environments for JavaServer Faces.
An extensible architecture:
JSF architecture has been designed to be extensible.Extensible means additional functionality can be given on the top of JSF core i.e. we can customize the functionality. JSF UI components are customizable and reusable elements. You can extend standard components and create your own complex components like stylish calendar, menu bar etc.
Support for multiple client devices:Component developers can extend the component classes to generate their own component tag libraries to support specific client. JSF flexible and extensible architecture allows developers to do so.
Flexible rendering model:Renderer separates the functionality and view of the component. So we can create multiple renderers and give them different functionality to get different appearance of the same component for the same client or different .
International language support: Java has excellent support for internationalization . It allows you to localize messages with user specific locale. A locale is a combination of a country, a language, and a variant code. JavaServer Faces adopts this property and let you specify which locale your application supports. So you can display you messages in different languages.
Robust tool support:There are several standard tool vendors like Sun Java Studio Creator who provide robust tools that take advantages of JSF to create server side UI easily.
JSF Components
Components in JSF are elements like text box, button, table etc.. that are used to create UI of JSF Applications. These are objects that manage interaction with a user. You can create :
- Simple components, like text box, button and
- Compound components, like table, data grid .
A component containing many components inside it is called a compound component. Components help developers to create UIs by assembling a number of components , associating them with object properties and event handlers. Would u like to repeat the same code again & again and waste time if u want to create many tables in hundreds of pages in your web application? Not at all. Once you create a component, it’s simple to drop that component onto any JSP.
JSF allows you to create and use components of two types:
JSF allows you to create and use components of two types:
- Standard UI Components: JSF contains its basic set of UI components like text fields, check boxes , list boxes, panel , label, radio button etc. These are called standard components. For example:
UIForm represents a user input form that is a container of other components.
UICommand represents UI components like buttons, hyperlinks and menu items.
UIInput represents UI components like text input fields, numeric input fields. - Custom UI Components:Generally UI designers need some different , stylish components like fancy calendar, tabbed panes . These types of components are not standard JSF components. JSF provides this additional facility to let you create and use your own set of reusable components .These components are called custom components.
One of the greatest power of JSF is to support third party components .Third party components are custom components created by another vendor. Several components are available in the market ,some of them are commercial and some are open source . You can use these pre-built & enhanced components in UI of your web application .Suppose u need a stylish calendar , u have an option to take it from third party rather than creating it .This will help you to save your time & cost creating effective & robust UI and to concentrate on business logic part of web application.
If u want to create custom components then its necessary to either implement UIComponent interface or extend UIComponentBase class that provides default behavior of components. These may be responsible for its own display or the renderer is used for its display. These components are stored in component tree on the server and they maintain state in between client requests. These components are manipulated on the sever in java code.
So the final conclusion of using third party components is that a more attractive , robust and functional UI can be created with fewer time, cost and man power.
JSF Tags
JSF application typically uses JSP pages to represent views. JSF provides useful special tags to enhance these views. Each tag gives rise to an associated component. JSF provides 43 tags in two standard JSF tag libraries:- JSF Core Tags Library and
- JSF Html Tags Library
Even a very simple page uses tags from both libraries.<%@ taglib uri=”http://java.sun.com/jsf/core “ prefix=”f” %>
<%@ taglib uri=”http://java.sun.com/jsf/html “ prefix=”h” %>
<f:view>
<h:form>
……………
……………
</h:form>
</f:view>
In the above code fragment we have imported two JSF tag libraries with the help of taglib directive. JSF Core Tag Library contains set of JSF core tags while JSF Html Tags Library contains set of html tags. Prefix is used to use tags defined in tag library. Here we are using conventional names f and h for Core & Html tags respectively. We have the choice to choose any name for the prefixes.- JSF Html Tags:
These tags represent html components like text fields, buttons, form.
Html tags can be divided into following categories:
Inputs (inputText, inputTextarea)
Outputs (outputText, outputLabel)
Commands (commandButton)
Selections (selectOneRadio, selectOneListbox, selectOneMenu for radio buttons, list boxes, menu etc)
Layouts (panelGrid)
Data table (dataTable)
Errors and messages (message, messages)
Some examples have been given below to understand how to use these tags and its attributes:<h:inputText id=”ID1” value=”value”/>
creates a single line text input control where id attribute is used to uniquely identify the component rendered by this tag and value attribute sets the current value of the component.<h:outputText id="ID2" value="Welcome"/>
creates a single line text output where id attribute uniquely identifies the rendered component and current value is set by value attribute .
<h:commandButton
id="submit"
value="go"
action="nextPage">
</h:commandButton>
creates a command button where value attribute sets the value that is displayed on the button when it is rendered and action attribute is used to invoke a method defined in backing bean when a user does an action on the component .According to the return of the invoked method it is determined which view is to be displayed next.
In JSF Html Tag Library there are 25 core tags .All JSF Html Tags :
- column creates column in a dataTable
- commandButton creates button
- commandLink creates link that acts like a pushbutton
- dataTable creates a table control
- form creates a form
- graphicImage displays an image
- inputHidden creates hidden field
- inputSecret creates input control for password
- inputText creates text input control (single line)
- inputTextarea creates text input control (multiline)
- message displays the most recent message for a component
- messages displays all messages
- outputFormat creates outputText, but formats compound messages
- outputLabel creates label
- outputLink creates anchor
- outputText creates single line text output
- panelGrid creates html table with specified number of columns
- panelGroup used to group other components where the specification requires one child element
- selectBooleanCheckbox creates checkbox
- selectManyCheckbox creates set of checkboxes
- selectManyListbox creates multiselect listbox
- selectManyMenu creates multiselect menu
- selectOneListbox creates single select listbox
- selectOneMenu creates single select menu
- selectOneRadio creates set of radio buttons
- JSF Core Tags:
These tags allows you to take advantages of features of JSF framework, like validation, conversion , event handling. Core library is stepchild of Html library. i.e. core library supports the html library. Core tag library also contains tags for views and sub-views , loading resource bundle, adding arbitrary text to a page. Some examples of JSF core tags are:
f: view tag is used to create top level view
f: subview tag is used to create subview of a view.
f: validator tag is used to add a validator to a component.
f: converter tag is used to add an arbitrary converter to a component.
f: actionListener tag is used to add an action listener to a component.
f:valueChangeListener tag is used to add a valuechange listener to a component
Some examples have been given below to understand how to use these tags:
<f:view locale="en">
<h:outputText value="label" />
</f:view>
f: view tag is used to create top level view and is a container for all JSF component tags on a page. Where locale attribute provides several options for presenting localized views of your application. Here "en" represents English and if we give velue "fr" to locale attribute then french view will be displayed. So this attribute is useful for internationalization purpose.
<f:view>
<h1>head</h1>
<p>view</p>
<f:subview id="sub_id">
<c:import url="second.jsp" />
</f:subview>
</f:view>
Here f:subview tag is like container for the JSF components contained in an included JSP page (second.jsp).<h:inputText id="txt_id"
value="txt_value">
<f:validator validatorId="Txt_Validator" />
</h:inputText>
The Validator tag registers a Validator on the component associated with the enclosing tag. In validatorId field, we give the value of one of the validator-id element of a validator in your Faces configuration file.
In JSF Core Tag Library there are 18 core tags .
All JSF Core Tags:- f :view Creates the top-level view
- f:subview Creates a subview of a view
- f:attribute Adds an attribute to a component
- f:param Constructs a parameter component
- f:converter Adds an arbitrary converter to a component
- f:converterDateTime Adds a datetime converter to a component
- f:converterNumber Adds a number converter to a component
- f:actionListener Adds an action listener to a component
- f:valueChangeListener Adds a valuechange listener to a component
- f:validator dds a validator to a component
- f:validateDoubleRange Validates a double range for a component’s value
- f:validateLength Validates the length of a component’s value
- f:validateLongRange Validates a long range for a component’s value
- f:facet Adds a facet to a component
- f:loadBundle Loads a resource bundle, stores properties as a Map
- f:selectitems Specifies items for a select one or select many component
- f:selectitem Specifies an item for a select one or select many component
- f:verbatim Adds markup to a JSF page
JSF Life Cycle
Life cycle of a JSF web application starts when user makes a request. On submission of a page various further tasks are performed like validation of data provided in components in the view, data conversion according to types specified on server side etc. So series of steps that an application follows is called life cycle.
A JSF application typically follows six steps in its life :1. Restore view phase : This phase starts when a user requests a JSF page by clicking a link, button etc. In this phase view generation of the page, binding of components to its event handlers and validators are performed and view is saved in the FacesContext object. The FacesContext object contains all the state information JSF needs to manage the GUI component's state for the current request in the current session. The FacesContext stores the view in its viewRoot property.All the JSF components are contained by viewRoot for the current view ID. Component tree of a page is newly built or restored.
A request comes through the FacesServlet controller. The controller checks the request and takes the view ID i.e. name of the JSP page. View ID is used to look up the components in the current view. JSF controller uses this ID if the view already exists . If the view doesn't already exist, the JSF controller creates it. The created view contains all components.2. Apply request values phase :
The purpose of this phase is for each component to retrieve its current state. After restoring of component tree in previous phase each component in the tree retrieves its new value and store it locally. Component values are typically retrieved from the request parameters.If immediate attribute of a component is set to true, then the validation, conversion, and events associated with the component is processed in this phase.
If a component's immediate event handling property is not set to true, the values are converted. Suppose field is bound to be an Integer property, the value is converted to an Integer. An error message associated with the component is generated if this conversion fails, and queued in the FacesContext. This message will be displayed during the render response phase, along with any validation errors resulting from next process validation phase.
At the end of this phase, the components are set to their new values, and messages and events have been queued.3. Process validations phase :
During this phase local values stored for the component in the tree are compared to the validation rules registered for the components. If local value is invalid, an error message is added to FacesContext, and the component is treated invalid then JSF proceeds to the render response phase and display the current view showing the validation error messages. If there were conversion errors from the apply request values phase, the messages for these errors are also displayed. If there are no validation errors, JSF proceeds ahead to the update model values phase.4. Update model values phase :
After confirming that data is valid in the previous phase local values of components can be set to corresponding server side object properties i.e. backing beans. So bean properties will be updated .If the local data cannot be converted to the types specified by the bean properties, the life cycle proceeds directly to the render response phase and errors are displayed.5. Invoke application phase :
Before this phase the component values have been converted, validated, and applied to the bean objects, so you can now use them to execute the application's business logic. Application-level code is executed such as submitting a form or linking to another page.For example user moves to the next page you will have to create a mapping in the faces-config.xml file. Once this navigation occurs, you move to the final phase of the lifecycle.6. Render response phase:
In this phase JSP container renders the page back to the user,if jsp is used by application i.e. view is displayed with all of its components in their current state.If this is an initial request, the components will be added to the component tree. If this is not an initial request, the components are not added because they are already added to the tree.The state of the response is saved after rendering of the content of the view, so that subsequent requests can access it and it is available to the restore view phase.
JSF Architecture
JSF was developed integrating MVC design pattern so that applications can be designed well with greater maintainability. To understand this fact we need to understand what is MVC design pattern, how MVC helps to design an application well and how can we make our web application easy to maintain.
The MVC design pattern splits an application design into three separate parts:Model : handles data and logic.View : handles output (presentation)Controller: handles processing of an application.MVC model’s purpose is to separate model and presentation to enable developers to set focus on their core skills and collaborate more clearly. If you have to create many pages for presentation then you have to concentrate only on view layer rather than model and controller layer because you can reuse code for controller and model.
In the same way if you want to change the code for model then you typically need not to change view layer.
Controllers are used to process user actions. In this process layer model and views may be changed.The best advantages of JSF is that it is both a Java Web user-interface standard and a framework that fits well with the Model-View-Controller (MVC) design pattern. It offers a clean separation between presentation and behavior. MVC pattern helps persons of different skill sets to work separately so tasks can be completed in parallel. UI can be created by page author using reusable UI components and business logic part can be implemented using managed beans.
JSF Renderers
After creating JSF components, it is also necessary for each component to be rendered to the client so that it can be visible to the client’s device. Each of the tag gives rise to an associated component. A renderer is a type of class that is responsible for encoding and decoding components. Encoding displays the component while decoding translates the user’s input into components value i.e. transform it into values the component can understand.
Now a days there are many devices that are web enabled. So application developers have challenge to develop components that can work across various platforms. For example, if we have an application that works on standard web browser and we want to extend it to make it enable to work on a WAP device. So, to handle this case we need components to be rendered in more than one way. Here JSF can help you . It is a simple task for JSF. Solution is to develop separate renderers for the component. JSF components use different renderers depending on the device used.
Encoding:
For example: Suppose we have used h:inputText tag . So the renderer of the component associated with this tag produces the following output:<input type=”text” name=”ID” value=”current_value”/>This is called encoding. The encoded page is sent to the browser and displayed.
Decoding:
Now if fields in form are filled by user and page is submitted by clicking the button, the browser sends the form data to the web server as a “POST” request”. POST” request contains form data and URL of the form. This form data is placed in hash table and can be accessed by all components. Each component gets a chance to look that hash table to interpret the form data. This is called decoding.Html output Tag handler asks each component to render itself. Tag handler call two rendering methods for each component :1-encodeBegin() in doStartTag() and2-encodeEnd() in doEndTag().Opening tag, like <form> , is written by encodeBegin() method and closing tage </form>, is written by encodeEnd() method. Single tag, like <input>, that dosen’t require separate opening and closing tag is also written by encodeEnd() method.
JSF tag handler may call third rendering method encodeChildren().if rendersChilden property of component is set to true i.e. if component has child components(compound component). For example: Html table component composed of input field components as column values for each row. So for a complex component tag handler calls encodeBegin(), then encodeChildren() and encodeEnd() on the component.If the child component also has its own children component then encodeChildren() method calls encodeBegin() and encodeEnd() on the child component.Some components renders itself (Direct rendering) and some components uses renderer to render itself (Delegated rendering). So both are different. If component uses renderer, then JSF calls encoding methods of the renderer, not the encoding method of the component. Which renderer will be used is determined by getRenderer() method of the component. So rendering of UI components is separated out that makes it pluggable with other possible rendering i.e.if we want a new functionality, like a new look and feel or rendering output to different client types, then its easy to add or plug a new renderer.Render kit :
Component classes generally transfer the task of generating output to the renderer. All JSF components follow it. Render kit is a set of related renderers. javax.faces.render.RenderKit is the class which represents the render kit.The default render kit contains renderers for html but it’s up to you to make it for other markup languages.Render kit can implement a skin (a look & feel).Render kit can target a specific device like phone, PC or markup language like HTML,WML, SVG. This is one of the best benefit of JSF because JSF doesn't limit to any device or markup.
Sometimes we may wish to customize the renderers of an existing RenderKit and sometimes create our own RenderKit. We typically create renderers for our custom components.In this case we have to register renderers with existing RenderKits in JSF configuration file faces-config.xml.This renderer should define renderer-type of the original component. Also, you should provide the renderer-class that points to your custom renderer. The renderer class should extend javax.faces.render.Renderer class.
<render-kit>
<renderer>
<renderer-type>........</renderer-type>
<renderer-class>........</renderer-class>
</renderer>
</render-kit>
The information mentioned in configuration file registers the renderer with the default html RenderKit. UI component's geRendererType() method is called that returns a string to identify the type of renderer that would be used by component and to see if it should delegate rendering to a renderer. If no matching render type is found then component renders itself without delegating to any renderer.
<render-kit>
<render-kit-id>...........</render-kit-id>
<render-kit-class>........</render-kit-class>
<renderer>
<renderer-type>.........</renderer-type>
<renderer-class>........</renderer-class>
</renderer>
</render-kit>In this case, configuration file shows how to register the renderer (for ex. ButtonRenderer) specified in <renderer-class> which renders a component (for ex. Button) specified in <renderer-type> to a client (for ex. SVG) specified in <render-kit-id>.
Standard render kits:
JSF defines a standard RenderKit and set of associated Renderers that generate html markup. Renderer will be determined and handled automatically according to the tag used.
Display Data from Database in JSF Application
Developing JSF ApplicationIn this section, we are going to display data from database in JSF based web applications.ThedataTable
tag is used to create table on the page. The component is rendered as an html <table> element. UIColumn child components are responsible for rendering columns of the table. In these columns you can put any type of component like input text box, output text, command button etc.<h:column> tag is used to create column. There can be many column tags within dataTable tag. You can set header and footer in this table. For this<f:facet> tag is used. data table component and its children column component can use header and footer facet.This section provides you the code to which uses this tag and some of its attributes. It uses backing bean that supplies data to the data table to be rendered to the cells of the columns of the table.Code Description :1.Create a web page "data.jsp" for display data.<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view><html>
<head>
</head>
<body>
<center>
<br><br><br>
<h:dataTable id="dt1" value="#{tableBean.perInfoAll}" var="item" bgcolor="#F1F1F1" border="10" cellpadding="5" cellspacing="3" rows="4" width="50%" dir="LTR" frame="hsides" rules="all" summary="This is a JSF code to create dataTable." >
<f:facet name="header">
<h:outputText value="This is 'dataTable' demo" />
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="First Name" />
</f:facet>
<h:outputText style="" value="#{item.firstName}" ></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Last Name"/>
</f:facet>
<h:outputText value="#{item.lastName}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Username"/>
</f:facet>
<h:outputText value="#{item.uname}"></h:outputText>
</h:column>
<f:facet name="footer">
<h:outputText value="The End" />
</f:facet>
</h:dataTable><br>
</center>
</body></html></f:view>
2. Create a Bean class "TableBean.java".package opensourzesupport;
import java.sql.*;
import java.util.*;
public class TableBean {
Connection con ;
Statement ps;
ResultSet rs;
private List perInfoAll = new ArrayList();
public List getperInfoAll() {
int i = 0;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdetails","root","root");
ps = con.createStatement();
rs = ps.executeQuery("select * from user");
while(rs.next()){
System.out.println(rs.getString(1));
perInfoAll.add(i,new perInfo(rs.getString(1),rs.getString(2),rs.getString(3)));
i++;
}
}
catch (Exception e)
{
System.out.println("Error Data : " + e.getMessage());
}
return perInfoAll;
}
public class perInfo {
String uname;
String firstName;
String lastName;
public perInfo(String firstName,String lastName,String uname) {
this.uname = uname;
this.firstName = firstName;
this.lastName = lastName;
}
public String getUname() {
return uname;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
}3. Mapping for Bean class "faces-config.xml".<?xml version="1.0"?>
<faces-config>
<managed-bean>
<managed-bean-name>tableBean</managed-bean-name>
<managed-bean-class>opensourzesupport.TableBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>4.web.xml<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<!-- Faces Servlet -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>
<!-- Faces Servlet Mapping -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>Output :Database Table : "user"
JSF HTML Tag Reference
JSF HTML tags are used for design the page by using server side code. This tag is used by specifying the uri and prefix attribute of the taglib directive at the top of your JSP file. These are illusrated below as follows:http://java.sun.com/jsf/htmlThis is the uri for the JSF html tags. And for the prefix value commonly "h" is used but you can put anything as value of the prefix attribute of the taglib directive. When you declare any html tag as a JSF tag then you should write the tag as follows:<htmlprefixvalue:tagName attribute1="value" attribute2="value"></htmlprefixvalue:tagName attribute1="value" attribute2="value">.This is the syntax of specifying the html tag as a jsf tag. You can take an example of creation an input box by using jsf html tag as follows:If the prefix value is "h" then the syntax will be seen like : <h:inputText value="This is a text box."></h:inputText>.All the html tags have been used in the Rose India JSF Tutorial as you will get one by one ahead. You can skip for next section for getting html tags overview with complete code examples that can be used directly in your web application for creating several html components as the need of your application.
JSF column Tag
JSF html column tag which is used for creating columns of a table. This tag creates a data column inside a data table. By this table you can specify number of column and fix these with some specific values. You can specify the value for specific column by using data array. JSF data table creates multiple rows up to the length of array or number of elements associated with the data table.This section provides you a complete code of a program in which the column tags are used inside the data table. This program will help you for the procedure of using column tag for creating columns in a table.Code Description:<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:view>
<html>
<head><title>jsf h:column example</title></head>
<body>
<h:dataTable border="1">
<f:facet name="header">
<h:outputText value="This is header."/>
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="Student"/>
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Marks" />
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Percent" />
</f:facet>
</h:column>
<f:facet name="footer">
<h:outputText value="This is footer."/>
</f:facet>
</h:dataTable>
</body>
</html>
</f:view>Rendered Output:HTML Source Code:<html> <head><title>jsf h:column example</title></head> <body> <table border="1"> <thead> <tr><th colspan="3" scope="colgroup">This is header.</th></tr> <tr> <th scope="col">Student</th> <th scope="col">Marks</th> <th scope="col">Percent</th> </tr> </thead> <tfoot> <tr><td colspan="3">This is footer.</td></tr> </tfoot> <tbody> </tbody> </table> </body> </html>
JSF column tag has some attribute for different purposes. These attributes are explained below:- rendered: This is an attribute of the column tag that is optional. This attribute can hold Stringtyped value. This attribute value indicates that the component should be rendered during the rendering period.
- binding: This attribute is also optional and take a String typed value. Specified value is linked with the backing bean through the attribute of the tag.
- id: This attribute of the column tag is specified only for identification of the specific tag.
JSF commandButton Tag
This tag renders an HTML submit button. This button can be associated with bean. You can perform any operations at particular event by associating actionListener class for event handling. You can do any thing with JSF component by the external resources like showing message from the message bundle and handling form data after submission the form by backing bean.This section also providing a program with complete code which display a command button inside a form. When you will click on the button, it's action attributes send a value "page1" to the faces-config.xml file where navigation has been made with the "page1" value. And the navigation refers the control to the Index page.Code Description:<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:view>
<html>
<head><title>jsf h:commandButton example</title></head>
<body>
<h:form>
<h:commandButton value="Go To Index Page." action="page1" />
</h:form>
</body>
</html>
</f:view>Rendered Output:HTML Source Code:<html> <head><title>jsf h:commandButton example</title></head> <body> <form id="_id0" method="post" action="/ h-tags/pages/commandButton/commandButton.jsf" enctype="application /x-www-form-urlencoded"> <input type="submit" name="_id0:_id1" value="Go To Index Page." /> <input type="hidden" name="_id0" value="_id0" /> </form> </body> </html>
JSF commandButton tag has some attribute for different purposes. These attributes are explained below:- action: This attribute holds a value for passing values from the page to the faces-config.xml file where the operation or navigation from the page to another page is decided.
- actionListener: The actionListener attribute of the commandButton tag is used to assign an action listener method from backing bean that performs the specific operation.
- id: Value of the attribute is used for identifying the component uniquely. This attribute must have a unique value in the closest container.
- immediate:It's value is a boolean value that indicates for the component events that should be sent to registered event listeners immediately. The immediate attribute allows you to turn off validation for a particular component.
- rendered: This attribute takes a boolean value that indicates for the rendering it or not in the view.
- value: This is the attribute holding the default value for the component whether it is specified directly or by the backing bean or any other external resources like message bundle.
- accesskey: This is the html attribute which specify key by pressing that key the component will be focused and accessed.
- alt: This is also a html attribute that is used for showing the textual description on mouse over of the component.
- dir: This attribute sets the value which define the component text direction. It sets the value like "LTR" means "left-to-right" and "RTL" means "right to left" direction.
- disabled: This attribute takes a boolean value. If the value is true then the component will be disabled otherwise the component will be enable.
- image: This attribute takes a relative or absolute url of the image that has to be displayed on the component. The image attribute is used for showing image on the component.
- lang: It sets the code for the language to be used in the markup generated by this component.
- onblur: This attribute indicates the event of the component. As the value of this attribute is defined as a JavaScript method which has to be performed when the component loses the focus.
- onchange: Specified JavaScript method is executed when the value has changed on losing focus after gaining focus.
- onclick: In the attribute, a JavaScript method is specified that is called when the component is clicked by user.
- ondblclick: This attribute indicates for performing the specified operation when the component is clicked two times continuously (or double click).
- onfocus: The JavaScript method can be called for the component when the component is focused.
- onkeydown: The specified JavaScript method or operation is performed when the key is pressed down over the component.
- onkeypress: This is the event of the component. It indicates the key press event. You can call a JavaScript method on the event of the component whatever you have mentioned.
- onkeyup: The specified JavaScript method is executed when key is released over this component.
- onmousedown: Specified JavaScript method is executed when mouse is pressed down over the component or element.
- onmousemove: This attribute sets the JavaScript code to executed when the mouse pointer is moved within the component or element.
- onmouseout: This attribute sets the JavaScript code to execute when the mouse pointer is moved away from the element or the component.
- onmouseover: This attribute sets the JavaScript code to execute when the mouse pointer is moved inside the element or the component.
- onmouseup: This attribute sets the JavaScript code to executed when the mouse pointer is released from the component.
- onselect: When you select the text contained by the component or element then the value of the attribute (JavaScript code) will be executed.
- readonly: This attribute sets the boolean value for making the component read-only or not.
- style: If you want ot add any CSS with the component then you can put the style as the value of the attribute. Added CSS will be applied on for the component.
- styleClass: This attribute holds the CSS class name which is defined in the external style sheet.
- tabindex: This attribute sets the tab index for the component. When you press the TAB key then the component will be focused after focusing all those components whose tab index is less than the component.
- title: This attribute holds a string value that is shown as a tool-tip text of a component or element.
- type: This attribute tells the component type whether it is submit type or reset etc.
- binding: This attribute binds the specified value with the backing bean.
JSF commandLink Tag
JSF commandLink tag which is rendered as a anchor tag. And this tag behaves as a command button for the form submission and this tag is also used for the event handling purposes through the backing bean. This tag has text that can be labeled by some external resources like properties file from the message bundle.Here, you will see more about the commandLink tag of JSF how is it used in JSF programming. There is a program with the complete code of JSF has been given for understanding the procedure of using the tag.Code Description:<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:view>
<html>
<head><title>jsf h:commandLink example</title></head>
<body>
<h:form>
<h:commandLink value="Go for list of examples." action="page2" />
</h:form>
</body>
</html>
</f:view>Here, when your run the above program, output will be seen like the following image in which the text "Go for list of examples." is looking like a hypertext. This is not only a anchor tag. This link behaves like a command button. You can perform an action at the specific event.Rendered Output:When you run the above example, your JSF tags are converted in to HTML code that is given. Following html source code is for the above written JSF code.HTML Source Code:<html> <head><title>jsf h:commandLink example</title></head> <body> <form id="_id0" method="post" action="/h-tags/pages/commandLink/ commandLink.jsf" enctype="application/x-www-form-urlencoded"> <a href="#" onclick="document.forms['_id0']['_id0:_idcl'] .value='_id0:_id1'; document.forms['_id0'].submit(); return false;">Go for list of examples.</a> <input type="hidden" name="_id0" value="_id0" /><input type="hidden" name="_id0:_idcl" /> </form> </body> </html>
This JSF tag has some attributes these explained as follows:- accesskey: This attribute set the key for the component through which the component can be accessed. Specified key is also used for transferring focus from one component to the component where it mentioned in with the JSF commandLink tag.
- action: This is also an attribute of the JSF commandLink tag. This attribute is used for handling events from the backing bean or any other resources to invoke the component when the component is activated by user. This type of action event is completed through a action method of the backing bean class. This method will either return a boolean value true or false by whom the Java Server Faces MVC Framework is designed. And navigations are depended on generated events and actions.
- actionListener: This attribute sets a method-binding expression with a backing bean. This method handles events.
- binding: This attribute binds values with backing bean.
- charset: This attribute sets the character encoding for the document that linked to by the hyperlink.
- coords: When you are using the link with a client-side image map, this attribute sets the position and the shape of spot on the screen.
- dir: This attribute set the direction of the text. The value for the attribute is accepted as "LTR" (left to right) or "RTL" (right to left).
- hreflang: This attribute sets the language code for the resource linked to by the hyperlink.
- id: This attribute sets the name for the identification of the component. It's value will be unique in the closest naming container.
- immediate: It's value is a boolean value that indicates for the component events that should be sent to registered event listeners immediately. The immediate attribute allows you to turn off validation for a particular component.
- lang: It sets the code for the language to be used in the markup generated by this component.
- onblur: This attribute sets JavaScript code when the component loses the focus.
- ondblclick: This attribute sets the JavaScript code when the component has been double-clicked over the component.
- onfocus: This attribute sets the JavaScript code when the component receives focus.
- onkeydown: This attribute sets the JavaScript code when key is pressed down over the element.
- onkeypress: This attribute sets the JavaScript code when key is pressed and released over the element or the component.
- onkeyup: This attribute sets the JavaScript code when key is released over the element or component.
- onmousedown: Specified JavaScript method is executed when mouse is pressed down over the component.
- onmousemove: This attribute sets the JavaScript code to executed when the mouse pointer is moved within the component.
- onmouseout: This attribute sets the JavaScript code to execute when the mouse pointer is moved away from the element.
- onmouseover: This attribute sets the JavaScript code to execute when the mouse pointer is moved inside the element.
- onmouseup: This attribute sets the JavaScript code to executed when the mouse pointer is released from the component.
- rel: This attribute tells you about the relationship between the current document and the document linked to by the hyperlink. It's values are the list of the link types separated by space from each other.
- rev: This attribute identifies a reserve link from the document linked to by the hyperlink to the current document. It's values are a list of link types separated by space from each other.
- rendered: This attribute takes a boolean value that indicates for the rendering it or not in the view.
- shape: This attribute sets the shape of the hotspot for viewing on the screen during the client side image mapping. It's some valid value is "rect" for the rectangular region, "default" for the entire region, "circle" for the circular region and "poly" for the polygonal region.
- style: If you want ot add any CSS with the component then you can put the style as the value of the attribute. Added CSS will be applied on for the component.
- styleClass: This attribute holds the CSS class name which is defined in the external style sheet.
- tabindex: This attribute sets the tab index for the component. When you press the TAB key then the component will be focused after focusing all those components whose tab index is less than the component.
- target: This attribute set the identification of a frame in which the resource has to be displayed that is linked to by the hyperlink.
- title: This attribute holds a string value that is shown as a tool-tip text of a component or element.
- type: This attribute tells the component type whether it is submit type or reset etc.
- value: This attribute set the display value for the component. It will be directly or any other resources like the backing bean or a message bundle. You can manage the backing bean for the value of the component or element.
JSF dataTable Tag
This tag is used to create table on the page. The component is rendered as an html <table> element. UIColumn child components are responsible for rendering columns of the table. In these columns you can put any type of component like input text box, output text, command button etc.<h:column> tag is used to create column. There can be many column tags within dataTable tag. You can set header and footer in this table. For this <f:facet> tag is used. data table component and its children column component can use header and footer facet.We can associate this table element to backing bean. So we can obtain data from this backing bean and display it on the table. Association of backing bean can also be helpful for event handling purpose. Suppose we inserted command button in columns of the table then event handling can be applied here. If you want to customize the table then cascading stylesheet (CSS) can be used. This will help you to enhance the appearance of the table's headers, footer, rows, columns.This section provides you the code to which uses this tag and some of its attributes. It uses backing bean that supplies data to the data table to be rendered to the cells of the columns of the table.
code description :<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view><html><body>
<h:form>
<br><br><br>
<h:dataTable id="dt1" value="#{TableBean.perInfoAll}" var="item" bgcolor="#F1F1F1" border="10" cellpadding="5" cellspacing="3" first="0" rows="4" width="50%" dir="LTR" frame="hsides" rules="all" summary="This is a JSF code to create dataTable." >
<f:facet name="header">
<h:outputText value="This is 'dataTable' demo" />
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="id" />
</f:facet>
<h:outputText value="#{item.id}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="name"/>
</f:facet>
<h:outputText value="#{item.name}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="phone"/>
</f:facet>
<h:outputText value="#{item.phone}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="city"/>
</f:facet>
<h:outputText value="#{item.city}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="pin"/>
</f:facet>
<h:outputText value="#{item.pin}"></h:outputText>
</h:column>
<f:facet name="footer">
<h:outputText value="The End" />
</f:facet>
</h:dataTable><br><br>
</h:form>
</body></html></f:view>Rendered Output :
In this example we have used <h:dataTable> tag. This <h:dataTable> tag has many attributes to give form and shape to the table and getting data from backing bean's attribute to display this data to the columns of the table. <f:facet> tag is used to create a header and a
footer for a dataTable component and it can create the same for columns also. So in this example we have used facet tag in dataTabe tag to create header and footer of the table component and incolumn tag also to create header for column. In this example, "This is 'dataTable' demo" is the header and "The End" is the footer for the table and "id" "name" "phone" "city" "pin" are headers for columns. In his example we have populated data to the table from bean named"TableBean". It contains an attribute "perInfoAll" that is an array of objects of type "perInfo" class which contains some attributes like id, name, phone, city, pin that is to be displayed on the table. In the value attribute of dataTable tag, we have specified the binding expression to bind this component to the bean (value="#{TableBean.perInfoAll}"
) and value specified in var attribute is used to populate data to the column of the table from attributes defined in class perInfo (value="#{item.id}"
). The code for the bean has been given below (remember to specify it in faces-cocfig.xml file) :public class TableBean {
private perInfo[] perInfoAll = new perInfo[]{
new perInfo(101, "CHANDAN", "9891444444", "aaa", 11111),
new perInfo(102, "RAVI", "9911666666", "bbb" ,22222),
new perInfo(103, "JOHN", "9313888888", "ccc", 33333),
new perInfo(104, "ANDREW", "9911222222", "ddd" , 44444),
new perInfo(105, "SYMONDS", "9313999999", "eee", 55555),
};
public perInfo[] getperInfoAll() {
return perInfoAll;
}
public class perInfo {
int id;
String name;
String phone;
String city;
int pin;
public perInfo(int id, String name, String phone, String city, int pin) {
this.id = id;
this.name = name;
this.phone = phone;
this.city = city;
this.pin= pin;
}
public int getid() {
return id;
}
public String getname() {
return name;
}
public String getphone() {
return phone;
}
public String getcity() {
return city;
}
public int getpin() {
return pin;
}
}
}HTML Source Code:<html> <body> <form id="_id0" method="post" action="/dt/data.jsf;jsessionid =B95AF7B5F7D80BCB5638B91AC8154C33" enctype="application/x-www-form-urlencoded"> <br><br><br> <table id="_id0:dt1" bgcolor="#F1F1F1" border="10" cellpadding="5" cellspacing="3" dir="LTR" frame="hsides" rules="all" summary="This is a JSF code to create dataTable." width="50%"> <thead> <tr><th colspan="5" scope="colgroup">This is 'dataTable' demo</th></tr> <tr> <th scope="col">id</th> <th scope="col">name</th> <th scope="col">phone</th> <th scope="col">city</th> <th scope="col">pin</th> </tr> </thead> <tfoot> <tr><td colspan="5">The End</td></tr> </tfoot> <tbody> <tr> <td>101</td> <td>CHANDAN</td> <td>9891444444</td> <td>aaa</td> <td>11111</td> </tr> <tr> <td>102</td> <td>RAVI</td> <td>9911666666</td> <td>bbb</td> <td>22222</td> </tr> <tr> <td>103</td> <td>JOHN</td> <td>9313888888</td> <td>ccc</td> <td>33333</td> </tr> <tr> <td>104</td> <td>ANDREW</td> <td>9911222222</td> <td>ddd</td> <td>44444</td> </tr> </tbody> </table> <br><br> <input type="hidden" name="_id0" value="_id0" /> </form> </body> </html>
This tag has some attributes. These are listed below :- id : This is used to uniquely identify the table component. This must be unique within the closest parent component.
- value : It represents the value of the component. It represents the value over which iteration is to be done. It may be an array or any iterator object .
- var : This is the name of the variable created by the data table that represents the current item in the value. This attribute helps exposing the data in the rows of the table.
- bgcolor : This attribute is used to set the background color for the table.
- border : We can set the width of the table's border around the table.
- cellpadding : This sets the space between the content and the border of the cell.
- cellspacing : It specifies the amount of space to leave between cells.
- first : This is used to specify the row number of the first row from which displaying is to be started onwards. Suppose, this property is set to 3,displaying will be started from the third row of the underlying data.
- rows : This attribute specifies the number of rows to display. This displaying will be started from the index specified in the "first" attribute. If we set this attribute to zero then all rows will be displayed.
- width : This is used to set the width of the entire table. Its value is specified in %. Suppose we set it to 50% then this table will be shown in the 50% space of the width of your screen.
- dir : This attribute indicates the direction of the text to be displayed in the cell. It takes "LTR" (left-to-right) and "RTL" (right-to-left) values. If we don't specify this attribute then the content will be displayed in center.
- frame : This attribute specifyes which sides of the frame surrounding this table will be visible. This attribute can take some values shown below :
- none No side, Default Value
- above Top side only
- below Bottom side only
- hsides Top and bottom sides only
- vsides Right and left sides only
- lhs Left hand side only
- rhs Right hand side only
- box All four sides
- border All four sides
- rules : This attribute is used to draw lines between cells. It can take some values given below :
- none No rules, default value
- groups Between row groups
- rows Between rows only
- cols Between columns only
- all Between all rows and columns
- summary : You can specify summary of the purpose of the table.
- rendered : It takes boolean value.This indicates whether or not this component should be rendered. Its default value is "true". If it is set to false then it prevents rendering of this component to the page.
- captionClass : Space separated list of CSS class or classes that will be applied to any caption generated for this table.
- captionStyle : It specifies CSS style or styles to be applied when this caption is rendered.
- columnClasses : Comma seperated list of CSS classes that will be applied to the columns of this table.
- footerClass : This attribute takes Space-separated list of CSS style class or classes that will be applied to aheaderter generated for this table.
- headerClass : This attribute takes Space-separated list of CSS style class or classes that will be
applied to any header generated for this table. - rowClasses : It is a list of CSS classes applied to the rows of the table.These classes should be separated by comma. If we want to apply CSS class for individual rows then we can specify space separated list of CSS classes. Style classes are applied to rows in the same order that they are
defined. If we have two CSS classes then first class is applied to the first row and the second one is applied to the second. Then again in the third row, the first CSS is applied and so on. This process goes on till the last row of the table. - lang : It sets the base language of an element’s attributes and text i.e. the language used in the generated markup for this component.
- styleClass : It sets the name of CSS classor classes that is applied at the time of rendering the element.
- title : The title attribute is used to set the tooltip text to display for the rendered component.Tooltip describes an element when rendered to the client.
- binding : It is a value binding expression that is used to link component to a property in a backing bean.
- onclick : It sets the JavaScript code to execute when a pointer button is clicked over this element.
- ondblclick : It sets the JavaScript code to execute when a pointer button is double clicked over this element.
- onkeydown : It sets the JavaScript code to execute when a key is pressed down over this element.
- onkeypress : It sets the JavaScript code to execute when a key is pressed and released over this element.
- onkeyup : It sets the JavaScript code to execute when a key is released over this element.
- onmousedown : It sets the JavaScript code to execute when a pointer button is pressed down over this element.
- onmousemove : It sets the JavaScript code to execute when a pointer button is moved within this element.
- onmouseout : It sets the JavaScript code to execute when a pointer button is moved away from this element.
- onmouseover : It sets the JavaScript code to execute when a pointer button is moved onto this element.
- onmouseup : It sets the JavaScript code to execute when a pointer button is released over this element.
JSF form tag
This tag renders html form element which contains the data that is submitted with the form. This tag uses "POST" method. The components under the particular form i.e. children of the form only are processed. "id" attribute is used to uniquely identify the form. CSS can be used to make it more attractive.Code Description :<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:view>
<html>
<head><title>jsf h:form example</title></head>
<body>
<h:form>
<h:outputText value="Enter your name: " /></td>
<h:inputText value="#{StoreNameBean.personName}" />
<h:commandButton action="result" value="Say Hello" />
</h:form>
</body>
</html>
</f:view>Rendered Output :Html Source Code :<html>
<head><title>jsf h:form example</title></head>
<body>
<form id="_id0" method="post" action="/h-tags/pages/form/form.jsf" enctype="application/x-www-form-urlencoded">
Enter your name: </td>
<input type="text" name="_id0:_id2" />
<input type="submit" name="_id0:_id3" value="Say Hello" />
<input type="hidden" name="_id0" value="_id0" /></form>
</body>
</html>This tag contains some attributes that are discussed below :- id : This attribute is used to uniquely identify the element within the closest container.
- rendered : Its a boolean attribute. Its default value is true. It determines whether this component should be rendered or not.
- binding : It takes the value binding expression that is used to link the component to the property of the backing bean.
- dir : It is used to set the direction of the text to be displayed. It can take two values LTR(left to right) and RTL (right to left).
- lang : It is used to set the base language of the component when displayed.
- style : It is used to set the CSS style definition for the component.
- title : It is the standard html attribute. It is used to set the tooltip text for this component.
- styleClass : It is used to set the CSS class for the component.
- target : This is used to identify the name of the frame where the response generated by the server is displayed when we submit the form.
- accept : Its a comma separated list of content types that is handled by the server which processes this form.
- acceptcharset : It is used to list character encoding used for the data input by the user and that will be accepted by the user.
- enctype : This is used to set the content type of the data that will be submitted to the server.
- onclick : Script to be invoked when the element is clicked.
- ondblclick : It is used for Java Script code to be invoked when the element is double-clicked.
- onmousedown : It is used for Java Script code to be invoked when the pointing device is pressed over this element.
- onmouseup : It is used for Java Script code to be invoked when the pointing device is released over this element.
- onmouseover : It is used for Java Script code to be invoked when the pointing device is moved into this element.
- onmousemove : It is used for Java Script code to be invoked when the pointing device is moved while it is in this element.
- onmouseout : It is used for Java Script code to be invoked when the pointing device is moves out of this element.
- onkeypress : It is used for Java Script code to be invoked when a key is pressed over this element.
- onkeydown : It is used for Java Script code to be invoked when a key is pressed down over this element.
- onkeyup : It is used for Java Script code to be invoked when a key is released over this element.
- onreset : It is used for Java Script code to be invoked when form is reset.
- onsubmit : It is used for Java Script code to be invoked when form is submitted.
JSF graphicImage Tag
This displays the image on the page. This tag renders an html "img" element. This tag renders the image file stored in the location specified in the "value" attribute of "graphicImage"tag. If this image file is not present in the specified location then the value of the alt attribute is displayed instead of the desired image file. In this example, value attribute is set to the location "/image/rose.gif" in the web-application root directory and alt attribute is set to "The image could not be found.".So this image is displayed on the page, if there is any problem in getting this image file ("/image/rose.gif") then the text specified in the alt attribute ("The image could not be found.") is displayed on the page. We can set width, height of the image. If we want tooltip for this image to be displayed when focus comes to the image, then we can use title attribute. There are several attributes of this tag to give it different look and structure.This section provides you the code that uses this tag and some of its attributes to render the image on the page.
Code Description :<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<html>
<body>
<h:form><br>
<h:graphicImage id="gi" alt="The image could not be found." value="/image/rose.gif" width="250" height="250" title="This is demo for 'graphicImage' tag" ></h:graphicImage>
</h:form>
</body>
</html>
</f:view>Rendered Output :
Html Source Code :
<html>
<body>
<form id="_id0" method="post" action="/graphicImage/graphicImage.jsf"enctype="application/x-www-form-urlencoded"><br>
<img id="_id0:gi" src="/graphicImage/image/rose.gif" alt="The image could not be found." height="250" title="This is demo for 'graphicImage' tag" width="250" />
<input type="hidden" name="_id0" value="_id0" />
</form>
</body></html>All attributes of graphicImage tag have been described below:- id : This is the identifier for the component. This must be the unique value within the closest parent component.
- alt : This is standard html attribute. This is the alternate textual value to be displayed in the absence of the image file specified in the value attribute.
- value : This attribute takes context relative URL to the image. URL is called relative to the context path of the web-application if URL starts with '/'. This image is rendered, if present, on the page.
- url : Its an alias for the value attribute.
- width : It is used to set new width of the image over the natural width.
- height :It is used to set new height of the image over the natural height.
- title : This is standard html attribute. It sets the tooltip for the component.
- rendered : It takes boolean value. Its default value is "true". It indicates whether the component should be rendered or not.
- dir : It sets the direction of the text to be displayed. It can take two values "LTR" (Left to Right) and "RTL" (Right to Left).
- lang : This is a standard html attribute. It is used to describe the base language used in the markup generated for this component.
- ismap : This takes a boolean value. This is used to indicate whether this image is to be used as a server side image or not.
- onclick : It sets the Java Script code to be invoked when the element is clicked.
- ondblclick : It sets the Java Script code to be invoked when the element is double-clicked.
- onkeydown : It sets the Java Script code to be invoked when a key is pressed down over this element.
- onkeypress : It sets the Java Script code to be invoked when a key is pressed over this element.
- onkeyup : It sets the Java Script code to be invoked when a key is released over this element.
- onmousedown : It sets the Java Script code to be invoked when the pointing device is pressed over this element.
- onmousemove : It sets the Java Script code to be invoked when the pointing device is moved within this element.
- onmouseout : It sets the Java Script code to be invoked when the pointing device is moves out of this element.
- onmouseover : It sets the Java Script code to be invoked when the pointing device is moved into this element.
- onmouseup : It sets the Java Script code to be invoked when the pointing device is released over this element.
- style : This is used to set the CSS style definition which will be applied to the component when it is rendered.
- styleClass : This is used to set the CSS class which will be applied to the component when it is rendered.
- usemap : This is html map element. This describes the name of client side image map for which this element provides the image.
- binding : Its a value binding expression that is used to link the component to the backing bean property.
JSF inputHidden Tag
This tag is used to create the field that is invisible to the user. This is the field that is used to pass the variables from one page to another. It renders the html inputelement with the type attribute set to"hidden".
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<html>
<body>
<h:form><br>
<h:inputHidden id="ih" value="hv"></h:inputHidden>
</h:form>
</body>
</html>
</f:view>Rendered Output :There is no rendered output for this tag . This gives invisible element as an output.Html Scorce Code :
<html>
<body>
<form id="_id0" method="post" action="/inputHidden/inputHidden.jsf" enctype="application/x-www-form-urlencoded"><br>
<input id="_id0:ih" type="hidden" name="_id0:ih" value="hv" />
<input type="hidden" name="_id0" value="_id0" />
</form>
</body>
</html>There is a list of all attributes that can be used in this inputHidden tag:- id : This is set to uniquely identify the component. So this must be the unique value within the closest container.
- value : This is the current value of the component.
- binding : This is used to set the binding expression that is used to link the component to the backing bean's property.
- rendered : This is the boolean attribute that is set to describe that this component should be rendered or not at the time of render response phase.
- required : This is the boolean attribute. User is required to provide the value for the field or not at the time of submission of the form is indicated by this attribute.
- validator : It takes a method binding expression that represents validator method. This method is called to validate the value of the component.
- immediate : This is the boolean attribute. This is used to ensure that the events should be sent to the associated listener immediately. It should not be sent after validation phase.
- converter : It is used to register the converter instance to the component.
- valueChangeListener : It takes the method binding expression that notifies the value change listener method. It notifies this method when value is changed and new value is set for this component.
JSF inputSecret Tag
This tag is used to create a text box for having password that is secret. This text box shows only a symbol for every enteries. You can't understand the value of the text box by seeing.Here, you will see in the program code that the value of the inputSecret tag has been assigned "chandan" but by seeing it's output as given below, any one can't understand. This type of text box helps you to keep your data secret.Code Description:<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:view>
<html>
<head><title>jsf h:message example</title></head>
<body>
<h:inputSecret value="chandan" />
</body>
</html>
</f:view>Rendered Output:HTML Source Code:Following is the html code generated by the browser when your JSF program is run.<html> <head><title>jsf h:message example</title></head> <body> <input type="password" name="_id0" value="" /> </body> </html>
All attributes of the inputSecret tag are explained as follows:- accesskey: This is standard html attribute. It is used to set the access key for the element which is used to send the focus to the element when pressed.
- alt: This is used as an alternate text that is displayed when browser is not able to display the element.
- binding: It takes the value binding expression that is used to link the component to the property of the backing bean.
- converter: This specifies the converter for the component. This can be static value or EL expression.
- dir: It is used to set the direction of the text to be displayed. It can take two values LTR(left to right) and RTL (right to left).
- disabled: Its a boolean attribute. This is used to disable the element to receive focus, when it is set to true.
- id: This attribute is used to uniquely identify the element within the closest container.
- immediate: Its a boolean attribute. It is used to identify during which phase value change event should occur. If this attribute is set to true then in place of firing the event during the process validation phase, these event are sent immadiately at the end of apply request values phase.
- lang: It is used to set the base language of the component when displayed.
- maxlength: It is used to set the maximum length of character that can be input into the text field.
- onblur: It is used to set the java script code to execute when focus is lost from the element.
- onchange: It is used to set the java script code to execute when element is modified.
- onclick: Script to be invoked when the element is clicked.
- ondblclick: It is used for Java Script code to be invoked when the element is double-clicked.
- onfocus: It is used to set the java script code to execute when element receives the focus.
- onkeydown: It is used for Java Script code to be invoked when a key is pressed down over this element.
- onkeypress: It is used for Java Script code to be invoked when a key is pressed over this element.
- onkeyup: It is used for Java Script code to be invoked when a key is released over this element.
- onmousedown: It is used for Java Script code to be invoked when the pointing device is pressed over this element.
- onmousemove: It is used for Java Script code to be invoked when the pointing device is moved while it is in this element.
- onmouseout: It is used for Java Script code to be invoked when the pointing device is moves out of this element.
- onmouseover: It is used for Java Script code to be invoked when the pointing device is moved into this element.
- onmouseup: It is used for Java Script code to be invoked when the pointing device is released over this element.
- onselect: It is used to set the java script code to execute when text of the component is selected by the user.
- readonly: Its a boolean attribute. It is used to indicate the user that its value can't be modified, if it is set to true.
- redisplay: This is a boolean attribute. This is used to specify that the password, that have been entered previously, has to be rendered again or not. Its default value is "false"because we generally need not to do this for security reasons.
- rendered: Its a boolean attribute. Its default value is true. It determines whether this component should be rendered or not.
- required: Its a boolean attribute. It indicates that its value is required by the user before the submission of the form to the server. If it is set to true and value is not provided then an error message comes.
- size: It is used to set the width (in character) of the component.
- style: It is used to set the CSS style definition for the component.
- styleClass: It is used to set the CSS class for the component.
- tabindex: This is a standard html attribute. It is used to set the order of receiving the focus on the movement of TAB key by the user.
- title: It is the standard html attribute. It is used to set the tooltip text for this component.
- validator: It takes the method binding expression. This expression represents the validator method. This method is called at the time of validation of the component.
- value: This is to set the current value of the component.
- valueChangeListener: This also takes a method binding expression. This expression represents value change listener method. This method will be called when new value is set for this component.
No comments:
Post a Comment