Java Server Faces or JSF for short is another new exciting technology for developing web applications based on Java technologies. This JSF Introduction section 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.
What is JSF?
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 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.
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 TagsJSF 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 CycleIn this we will understand the life cycle of JSF application.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 renderershould 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.First Java Server Faces Tutorial (JSF) – Eclipse
This
tutorial facilitates the first steps with the quite new framework
JavaServer Faces (JSF). Step by step an example application (a
library) will be created, which illustrate the different elements of
the framework.The
example application will provide the following functionality.- Display
a book overview (list of books) - Add,
edit and delete a book
Generals
Author:Sascha
WolskiDate: December, 21 2004Source
code:The
sources do not contain any project files of eclipse or libraries.
Create a new project following the tutorial, add the libraries as
explained in the tutorial and then you can copy the sources in your
new project.PDF Version des Tutorials:Development
ToolsEclipse
3.xMyEclipse
plugin 3.8(A
cheap and quite powerful Extension to Eclipse to develop Web
Applications and EJB (J2EE) Applications. I think that there is a
test version availalable at MyEclipse.)Application
ServerJboss
3.2.5You
may use Tomcat here if you like.Create a JavaServer faces project
Create a new web project. File
> New > Project.Set
a nice name and add the JSTL Libraries to the project.Add
the JavaServer faces Capabilities. Right click on the project and
choose MyEclipse > Add JSF
Capabilities.The class Book
Add an new package de.laliluna.tutorial.library
und create a new class named Book.Open the class and add the following private
properties:- id
- author
- title
- available
Generate a getter- and setter-method for each
property. Right click on the editor window and choose Source
> Generate Getter- and Setter Methods.Furthermore you have to add a constructor, which
set the properties if you initialisize the instance variable of the
newly object.The following source code show the class book.public class Book implements Serializable {<br><br> // ------------------ Properties --------------------------------<br> private long id;<br> private String author;<br> private String title;<br> private boolean available;<br><br> // ------------------ Constructors --------------------------------<br> public Book(){}<br> public Book(long id, String author, String title, boolean available){ <br> this.id = id;<br> this.author = author;<br> this.title = title;<br> this.available = available;<br> }<br><br> // ------------------ Getter and setter methods ---------------------<br><br> public String getAuthor() {<br> return author;<br> }<br> public void setAuthor(String author) {<br> this.author = author;<br> }<br> public boolean isAvailable() {<br> return available;<br> }<br> public void setAvailable(boolean available) {<br> this.available = available;<br> }<br> public long getId() {<br> return id;<br> }<br> public void setId(long id) {<br> this.id = id;<br> }<br> public String getTitle() {<br> return title;<br> }<br> public void setTitle(String title) {<br> this.title = title;<br> } <br>}
Add a getter and setter for the class./ * Set the properties * @param book */ public void setBook(Book book){ this.setId(book.getId()); this.setAuthor(book.getAuthor()); this.setTitle(book.getTitle()); this.setAvailable(book.isAvailable()); } / * @return book object / public Book getBook(){ return new Book(this.getId(), this.getAuthor(), this.getTitle(), this.isAvailable()); }
The database class
We use a class to provide some test data
without using a database. Download the sample application of this
tutorial and copy the class SimulateDB.java
find in the folder src/de/laliluna/tutorial/library/
in the package
de.laliluna.tutorial.library.The class BookList
Create a futher class BookList
in the package de.laliluna.library.
This class inlcudes the property books, which represent the list of
books. Generate a getter- and seter-method for the property books
and change the getter-method like the following.public class BookList { //
-——————————— Properties-———————————— Collection books; //-——————————— Getter and Setter-————————- / * @return collection of books */ public Collection getBooks(){ SimulateDB simulateDB = new SimulateDB(); / Holt sich die Session auf dem Externen Context / Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); / Lies alle B�cher auf der simulierten Datenbank aus / books = simulateDB.getAllBooks(session); return books; } /* * @param books The books to set. */ public void setBooks(Collection books) { this.books = books; } }Your package
explorer will look like the picture below.Action listener methods
To provide that a user can add, edit or
delete a book, we have to include the appropriate functionality. This
functionality will be implemented in action listener methods /
classes. If an event occur (ex.: a user clicks on a link) an action
listener method / class will be called and processed.Open the class Book and add four methods ,
which process the following functionality.- Initializise a book
- Edit a book
- Save a book
- Delete a book
Initialize a book
/**<br> * Initial the properties of the class with null<br> * @param event<br> */<br>public void initBook(ActionEvent event){<br><br> /*<br> * init the book object<br> */<br> this.setBook(new Book());<br>}
Edit a book
/ * Get the book to edit and assign it to the bean * * @param event */ public void selectBook(ActionEvent event){ SimulateDB simulateDB = new SimulateDB(); / * Get the session map of the external context / Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); / * Find the UIParameter component by expression / UIParameter component = (UIParameter) event.getComponent().findComponent(“editId”); / * parse the value of the UIParameter component / long id = Long.parseLong(component.getValue().toString()); / * get the book by id and set it in the local property / this.setBook(simulateDB.loadBookById(id, session)); }
Save a book
/ * Add or update the book in the simulated database. * If the book id is not set the book will be added * otherwise the book will be updated * * @param event */ public void saveBook(ActionEvent event){ SimulateDB simulateDB = new SimulateDB(); / * Get the session map of the external context / Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); / * Add or update the book in the simulated database / simulateDB.saveToDB(this.getBook(), session); }
Delete a book
/ * Delete a book in the simulated database * * @param event */ public void deleteBook(ActionEvent event){ SimulateDB simulateDB = new SimulateDB(); / * Get the session map of the external context / Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); / * Find the UIParameter component by expression / UIParameter component = (UIParameter) event.getComponent().findComponent(“deleteId”); / * parse the value of the UIParameter component / long id = Long.parseLong(component.getValue().toString()); / * delete the book by id */ simulateDB.deleteBookById(id, session); }
The file
faces-config.xmlThe faces-config.xml is the central
configuration file of JavaServer faces. In this file you define the
workflow of the application (on which action which site will be
processed) , the managed bean classes by JSF and something more.The workflow of the library application
looks like the following.We define a navigation rule for this
workflow.Open the file faces-config.xml
and add the following configuration.<faces-config><br><br> <!-- Navigation rules --><br> <navigation-rule><br> <description>List of books</description><br> <from-view-id>/listBooks.jsp</from-view-id><br> <navigation-case><br> <from-outcome>editBook</from-outcome><br> <to-view-id>/editBook.jsp</to-view-id><br> </navigation-case><br> </navigation-rule><br><br> <navigation-rule><br> <description>Add or edit a book</description><br> <from-view-id>/editBook.jsp</from-view-id><br> <navigation-case><br> <from-outcome>listBooks</from-outcome><br> <to-view-id>/listBooks.jsp</to-view-id><br> <redirect/><br> </navigation-case><br> </navigation-rule><br></faces-config>
<navigation-rule>
Define a navigation rule<from-view-id>/listBooks.jsp</from-view-id>
Define the jsp file for which the containing navigation rule is
relevant.<navigation-case>
Define a navigation case<from-outcome>editBook</from-outcome>
Define a name for this navigation case<to-view-id>/listBooks.jsp</to-view-id>
Refers to the setted JSP File<redirect/>
All parameters saved in the request will be losed when you set this
tag.If you want to access the bean classes in
your JSP files, you have to register the bean classes in
faces-config.xmlAdd the following source code.<!— Managed beans
-> <managed-bean> <description> Book bean </description> <managed-bean-name>bookBean</managed-bean-name> <managed-bean-class>de.laliluna.tutorial.library.Book</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <managed-bean> <description> BookList Bean </description> <managed-bean-name>bookListBean</managed-bean-name> <managed-bean-class>de.laliluna.tutorial.library.BookList</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean><managed-bean>
Define a managed bean<managed-bean-name>bookBean</managed-bean-name>
Define a name for the managed bean. This name is used in the JSP
file.<managed-bean-class>de.laliluna.tutorial.library.Book</managed-bean-class>
Define the class which represent the bean.<managed-bean-scope>request</managed-bean-scope>
Define in which scope the bean is saved.Create the JSP files
In the first step we create a JSP file named
index.jsp, which forwards
the user to the list of books.index.jsp
<!DOCTYPE HTML PUBLIC "//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <jsp:forward page=“/listBooks.faces” /> </body> </html>
In the second step we create the book overview.listBooks.jsp
<%@ page language=“java” > <%@ taglib uri=“http://java.sun.com/jsf/html” prefix=“h” %> <%@ taglib uri=“http://java.sun.com/jsf/core” prefix=“f” %> < String path = request.getContextPath(); String basePath = request.getScheme()“://”request.getServerName()“:”request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”> <html> <head> <base href=“<%=basePath%>”> <title>List of books</title> </head> <body> <f:view> <h:form id=“bookList”> <h:dataTable id=“books” value=“#{bookListBean.books}” var=“book” border=“1”> <h:column> <f:facet name=“header”> <h:outputText value=“Author”/> </f:facet> <h:outputText value=“#{book.author}” /> </h:column> <h:column> <f:facet name=“header”> <h:outputText value=“Title”/> </f:facet> <h:outputText value=“#{book.title}” /> </h:column> <h:column> <f:facet name=“header”> <h:outputText value=“Available”/> </f:facet> <h:selectBooleanCheckbox disabled=“true” value=“#{book.available}” /> </h:column> <h:column> <f:facet name=“header”> <h:outputText value=“Edit”/> </f:facet> <h:commandLink id=“Edit” action=“editBook” actionListener=“#{bookBean.selectBook}”> <h:outputText value=“Edit” /> <f:param id=“editId” name=“id” value=“#{book.id}” /> </h:commandLink> </h:column> <h:column> <f:facet name=“header”> <h:outputText value=“Delete”/> </f:facet> <h:commandLink id=“Delete” action=“listBooks” actionListener=“#{bookBean.deleteBook}”> <h:outputText value=“Delete” /> <f:param id=“deleteId” name=“id” value=“#{book.id}” /> </h:commandLink> </h:column> </h:dataTable> <h:commandLink id=“Add” action=“editBook” actionListener=“#{bookBean.initBook}”> <h:outputText value=“Add a book” /> </h:commandLink> </h:form> </f:view> </body> </html>
<%@ taglib uri=“http://java.sun.com/jsf/html” prefix=“h” > <%@ taglib uri=“http://java.sun.com/jsf/core” prefix=“f” %>
With directive taglib
we include the JSF tag libraries<f:view>
Renders a view component. All others tags must be included within
this tag.<h:form id=“bookList”>
Renders a HTML form.<h:dataTable id=“books” value=“#{bookListBean.books}” var=“book” border=“1”>
Renders a HTML table. The tag is used to loop over a list of data
like a for loop. The
parameter value assign a
list of data, in our case the list of books of the library. With the
parameter var you define
the variable used to access a element (a book) of the list within the
tag (loop).<h:column> <f:facet name=“header”> <h:outputText value=“Author”/> </f:facet> <h:outputText value=“#{book.author}” /> </h:column>
Renders a column with a column header.<f:facet
name=“header”>
display the header.
<h:outputText
value=“Author”/>
print out a header label.
<h:outputText
value=“#{book.author}” /> refers
to the property author
of the current element of the list.<h:commandLink id=“Edit” action=“editBook” actionListener=“#{bookBean.selectBook}”>
Renders a HTML link, which submits the form. The parameter action
define the navigation case, which is processed, after the form
submits In our case the navigation case editBook, we have added befor
in the faces-config.xml, will be processed. We assign the action
listener method to the link with the parameter actionListener.
After the user submit the form the method will be processed.The last JSP file includes a form to add and
edit a book.editBook.jsp
<%@ page language=“java” %> <%@ taglib uri=“http://java.sun.com/jsf/html” prefix=“h” %> <%@ taglib uri=“http://java.sun.com/jsf/core” prefix=“f” %> < String path = request.getContextPath(); String basePath = request.getScheme()“://”request.getServerName()“:”request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”> <html> <head> <base href=“<%=basePath%>”> <title>Add / Edit a book</title> </head> <body> <f:view> <h:form> <h:inputHidden id=“id” value=“#{bookBean.id}”/> <h:panelGrid columns=“2” border=“1”> <h:outputText value=“Author:” /> <h:inputText id=“author” value=“#{bookBean.author}”> </h:inputText> <h:outputText value=“Title:” /> <h:inputText id=“title” value=“#{bookBean.title}”> </h:inputText> <h:outputText value=“Available:” /> <h:selectBooleanCheckbox id=“available” value=“#{bookBean.available}” /> </h:panelGrid> <h:commandButton value=“Save” action=“listBooks” actionListener=“#{bookBean.saveBook}” /> </h:form> </f:view> </body> </html>
<h:inputHidden id=“id” value=“#{bookBean.id}”/>
Renders a HTML hidden element. Value refers to the managed bean
bookBean and its property
id, which indicated in the
faces-config.xml.<h:panelGrid columns=“2” border=“1”>
Renders a HTML table with two columns.<h:inputText id="author" value="#{bookBean.author}">
Renders a HTML text field. Value refers to the property author
of our class Book.<h:commandButton value=“Save” action=“listBooks” actionListener=“#{bookBean.saveBook}” />
Renders a HTML submit button with the value save and the action
listBooks. The action listener method saveBook
will be processed if the user submit the form.Test the application
Start the jboss and deploy the project as
Packaged Archive.Call the project now
http://localhost:8080/LibraryWeb/
No comments:
Post a Comment