RSS

What is JSF?

23 Mar

1.  What is JSF (or JavaServer Faces)?

A server side user interface component framework for Java™ technology-based web applications.JavaServer Faces (JSF) is an industry standard and a framework for building component-based user interfaces for web applications.

JSF contains an API for representing UI components and managing their state; handling events, server-side validation, and data conversion; defining page navigation; supporting internationalization and accessibility; and providing extensibility for all these features.

2. What are the advantages of JSF? 

The major benefits of JavaServer Faces technology are:

  • JavaServer Faces architecture makes it easy for the developers to use. In JavaServer Faces technology, user interfaces can be created easily with its built-in UI component library, which handles most of the complexities of user interface management.
  • Offers a clean separation between behavior and presentation.
  • Provides a rich architecture for managing component state, processing component data, validating user input, and handling events.
  • Robust event handling mechanism.
  • Events easily tied to server-side code.
  • Render kit support for different clients
  • Component-level control over statefulness
  • Highly ‘pluggable’ – components, view handler, etc
  • JSF also supports internationalization and accessibility
  • Offers multiple, standardized vendor implementations

3. What are differences between struts and JSF?

In a nutshell, Faces has the following advantages over Struts:

  • Eliminated the need for a Form Bean
  • Eliminated the need for a DTO Class
  • Allows the use of the same POJO on all Tiers because of the Backing Bean

The primary advantages of Struts as compared to JavaServer Faces technology are as follows:

  • Because Struts is a web application framework, it has a more sophisticated controller architecture than does JavaServer Faces technology. It is more sophisticated partly because the application developer can access the controller by creating an Action object that can integrate with the controller, whereas JavaServer Faces technology does not allow access to the controller. In addition, the Struts controller can do things like access control on each Action based on user roles. This functionality is not provided by JavaServer Faces technology.
  • Struts includes a powerful layout management framework, called Tiles, which allows you to create templates that you can reuse across multiple pages, thus enabling you to establish an overall look-and-feel for an application.
  • The Struts validation framework includes a larger set of standard validators, which automatically generate both server-side and client-side validation code based on a set of rules in a configuration file. You can also create custom validators and easily include them in your application by adding definitions of them in your configuration file.

The greatest advantage that JavaServer Faces technology has over Struts is its flexible, extensible UI component model, which includes:

  • A standard component API for specifying the state and behavior of a wide range of components, including simple components, such as input fields, and more complex components, such as scrollable data tables. Developers can also create their own components based on these APIs, and many third parties have already done so and have made their component libraries publicly available.
  • A separate rendering model that defines how to render the components in various ways. For example, a component used for selecting an item from a list can be rendered as a menu or a set of radio buttons.
  • An event and listener model that defines how to handle events generated by activating a component, such as what to do when a user clicks a button.
  • Conversion and validation models for converting and validating component data.

4.  What are the available implementations of JavaServer Faces?

The main implementations of JavaServer Faces are:

  • Reference Implementation (RI) by Sun Microsystems.
  • Apache MyFaces is an open source JavaServer Faces (JSF) implementation or run-time.
  • ADF Faces is Oracle’s implementation for the JSF standard.

6. What typical JSF application consists of?

A typical JSF application consists of the following parts:

  • JavaBeans components for managing application state and behavior.
  • Event-driven development (via listeners as in traditional GUI development).
  • Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

7. What Is a JavaServer Faces Application?

JavaServer Faces applications are just like any other Java web application. They run in a servlet container, and they typically contain the following:

  • JavaBeans components containing application-specific functionality and data.
  • Event listeners.
  • Pages, such as JSP pages.
  • Server-side helper classes, such as database access beans.

In addition to these items, a JavaServer Faces application also has:

  • A custom tag library for rendering UI components on a page.
  • A custom tag library for representing event handlers, validators, and other actions.
  • UI components represented as stateful objects on the server.
  • Backing beans, which define properties and functions for UI components.
  • Validators, converters, event listeners, and event handlers.
  • An application configuration resource file for configuring application resources.

8. What is Managed Bean?JavaBean objects managed by a JSF implementation are called managed beans. A managed bean describes how a bean is created and managed. It has nothing to do with the bean’s functionalities.

9. What is Backing Bean?

Backing beans are JavaBeans components associated with UI components used in a page. Backing-bean management separates the definition of UI component objects from objects that perform application-specific processing and hold data.

The backing bean defines properties and handling-logics associated with the UI components used on the page. Each backing-bean property is bound to either a component instance or its value. A backing bean also defines a set of methods that perform functions for the component, such as validating the component’s data, handling events that the component fires and performing processing associated with navigation when the component activates.

10. What are the differences between a Backing Bean and Managed Bean?

Backing Beans are merely a convention, a subtype of JSF Managed Beans which have a very particular purpose. There is nothing special in a Backing Bean that makes it different from any other managed bean apart from its usage.

What makes a Backing Bean is the relationship it has with a JSF page; it acts as a place to put component references and Event code.

Backing Beans

Managed Beans

A backing bean is any bean that is referenced by a form. A managed bean is a backing bean that has been registered with JSF (in faces-config.xml) and it automatically created (and optionally initialized) by JSF when it is needed.
The advantage of managed beans is that the JSF framework will automatically create these beans, optionally initialize them with parameters you specify in faces-config.xml,
Backing Beans should be defined only in the request scope The managed beans that are created by JSF can be stored within the request, session, or application scopes

Backing Beans should be defined in the request scope, exist in a one-to-one relationship with a particular page and hold all of the page specific event handling code.In a real-world scenario, several pages may need to share the same backing bean behind the scenes.A backing bean not only contains view data, but also behavior related to that data.

11. What is view object?  

A view object is a model object used specifically in the presentation tier. It contains the data that must display in the view layer and the logic to validate user input, handle events, and interact with the business-logic tier. The backing bean is the view object in a JSF-based application. Backing bean and view object are interchangeable terms.


12. What is domain object model?

Domain object model is about the business object and should belong in the business-logic tier. It contains the business data and business logic associated with the specific business object.

13. What is the difference between the domain object model and a view object? 

In a simple Web application, a domain object model can be used across all tiers, however, in a more complex Web application, a separate view object model needs to be used. Domain object model is about the business object and should belong in the business-logic tier. It contains the business data and business logic associated with the specific business object. A view object contains presentation-specific data and behavior. It contains data and logic specific to the presentation tier.

14. What do you mean by Bean Scope?

Bean Scope typically holds beans and other objects that need to be available in the different components of a web application.

15.  What are the different kinds of Bean Scopes in JSF?

JSF supports three Bean Scopes. viz.,

  • Request Scope: The request scope is short-lived. It starts when an HTTP request is submitted and ends when the response is sent back to the client.
  • Session Scope: The session scope persists from the time that a session is established until session termination.
  • Application Scope: The application scope persists for the entire duration of the web application. This scope is shared among all the requests and sessions.

16. What is the difference between JSP-EL and JSF-EL?

JSP-EL

JSF-EL

In JSP-EL the value expressions are delimited by ${…}. In JSf-EL the value expressions are delimited by #{…}.
The ${…} delimiter denotes the immediate evaluation of the expressions, at the time that the application server processes the page. The #{…} delimiter denotes deferred evaluation. With deferred evaluation ,the application server retains the expression and evaluates it whenever a value is needed.

note:As of JSF 1.2 and JSP 2.1 ,the syntax of both expression languages has been unified.

17. What are The main tags in JSF?

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 (Sun Implementation) provides 43 tags in two standard JSF tag libraries:

  • JSF Core Tags Library.
  • JSF Html Tags Library.

18. How do you declare the managed beans in the faces-config.xml file?

The bean instance is configured in the faces-config.xml file:

<managed-bean>

<managed-bean-name>login</managed-bean-name>

<managed-bean-class>com.developersBookJsf.loginBean</managed-bean-class>

<managed-bean-scope>request</managed-bean-scope>

</managed-bean>

This means: Construct an object of the class com.developersBookJsf.loginBean, give it the namelogin, and keep it alive for the duration of the request.
19. How to declare the Message Bundle in JSF?

 

We can declare the message bundle in two ways:
(Let’s assume com.developersBookJsf.messages is the properties file)

 

    1. The simplest way is to include the following elements in faces-config.xml file:

    <application>

<resource-bundle>

<base-name>com.developersBookJsf.messages</base-name>

<var>message</var>

</resource-bundle>

</application>

2.  Alternatively, you can add the f:loadBundle element to each JSF page that needs access to the bundle:

   <f:loadBundle baseName = “com.developersBookJsf.messages” var=”message”/>

20. How to declare the page navigation (navigation rules) in faces-config.xml file ?

Navigation rules tells JSF implementation which page to send back to the browser after a form has been submitted. We can declare the page navigation as follows:

  <naviagation-rule>

<from-view-id>/index.jsp</from-view-id>

<navigation-case>

<from-outcome>login</from-outcome>

<to-view-id>/welcome.jsp</to-view-id>

</navigation-case>

</naviagation-rule>

This declaration states that the login action navigates to /welcome.jsp, if it occurred inside/index.jsp.

21. What if no navigation rule matches a given action?  

If no navigation rule matches a given action, then the current page is redisplayed.

22.  What are the JSF life-cycle phases?

The six phases of the JSF application lifecycle are as follows (note the event processing at each phase):

1.  Restore view
2.  Apply request values; process events
3.  Process validations; process events
4.  Update model values; process events
5.  Invoke application; process events
6.  Render response

23. Explain briefly the life-cycle phases of JSF? 

1. Restore View :   A request comes through the FacesServlet controller. The controller examines the request and extracts the view ID, which is determined by the name of the JSP page.
2. Apply request values  The purpose of the apply request values phase is for each component to retrieve its current state. The components must first be retrieved or created from the FacesContext object, followed by their values.
3. Process validations  In this phase, each component will have its values validated against the application’s validation rules.
4. Update model values  In this phase JSF updates the actual values of the server-side model ,by updating the properties of your backing beans.
5. Invoke application  In this phase the JSF controller invokes the application to handle Form submissions.
6. Render response  In this phase JSF displays the view with all of its components in their current state.

24. What does it mean by render kit in JSF?

A render kit defines how component classes map to component tags that are appropriate for a particular client. The JavaServer Faces implementation includes a standard HTML render kit for rendering to an HTML client.

25.  Is it possible to have more than one Faces Configuration file?

We can have any number of config files. Just need to register inweb.xml.
Assume that we want to use faces-config(1,2,and 3),to register more than one faces configuration file in JSF,just declare in the web.xml file

<context-param>

<param-name>javax.faces.CONFIG_FILES</param-name>

<param-value>

/WEB-INF/faces-config1.xml,

/WEB-INF/faces-config2.xml,

/WEB-INF/faces-config3.xml

</param-value>

</context-param>

Part-1 ——————————————————————————————————————

  1. What is JSF (Java Server Faces)?
    JavaServer Faces (JSF) is an application framework containing a rich and robust set of APIs and JSP custom tag libraries to simplify creating user interfaces for web based Java applications. Set of APIs represent user interface components and are responsible for managing their state, handling events, validating input. APIs also define page navigation, internationalization and accessibility. JSF includes  JSP custom tag library for including JSF interface within a JSP page.

So JSF offers a flexible and extensible architecture that makes easy creating reusable, complex server side UI components without limiting developers to a particular mark-up language, protocol, or client device by combining the UI component functionality with custom renderers. Here extensible means additional functionality can be given on the top of JSF core i.e. we can customize the functionality and reusable stands for being able to add and reuse components many times in the page.
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. So JSF can be think of a combination of two frameworks, Struts and Swing. Struts is a popular open source JSP-based Web application framework and Swing is a standard Java user interface framework for desktop applications. Like Struts, JSF provides Web application lifecycle management through a controller servlet (FacesServlet) and like Swing, JSF provides a rich component model complete with event handling and component rendering. JSF also ensures that applications are well designed with greater maintainability by integrating the well established Model-View-Controller (MVC) design pattern into its architecture. So it clearly separates behavior (Model) and presentation (View) in an application. This  separation enables a wide range of users Page authors(web-page designers), Application developersComponent writers,Application architects Tool vendors and allows members of team to focus on their own work only , resulting in division of labor and shorter development cycle.JSF has been developed by Java Community Process(JCP) that is a community of web application experts 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).
Facts about JSF can be summarized as below :

  1. JSF is standard web UI server side component framework for Java.
  2. Built on top of Servlet API.
  3. UI components are stored on the server.
  4. Easy use of third party components.
  5. Event driven programming model.
  6. Events generated by user are handled on the  server.
  7. Navigation handling.
  8. Can automatically synchronize UI components .
  9. JSF supports multiple client devices.
  10. JSF has extensible architecture.
  11. International language support.
  12. Extensive tool support (Sun, Oracle , IBM etc.).
  13. Rapid application development approach.
  • What is the significance of MVC model in JSF?
     JSF ensures that applications are well designed with greater maintainability by integrating the well established Model-View-Controller (MVC) design pattern into its architecture. So it clearly separates behavior (Model) and presentation of data (View) in an application. UI components represent View (Typically in JSP),managed beans represent Model and FacesServlet is the Controller in the JSF framework. All the requests are handled by this controller. Any request passes through and examined by FacesServlet that calls various actions on the model (managed beans). The separation of behavior and presentation enables a wide range of users Page authors( web-page designers), Application developersComponent writersApplication architects Tool vendors and allows members of team to focus on their own work only , resulting in division of labor and shorter development cycle.
  • Which plays role of controller in JSF?
    JSF integrates the well established Model-View-Controller (MVC) design pattern into its architecture. The purpose of MVC is to separate data (Model) and presentation of data (View) in an application. User requests are handled centrally by the controller that might result in changes in the model and views.  In JSF, UI components represent View layer and managed beans represent Model.FacesServlet is the Controller in the JSF framework. All the requests are handled by this controller. Any request passes through and examined by FacesServlet that calls various actions on the model (managed beans).

Part-2——————————————————————————————————————-

 
Who are the users of JSF technology?
JSF is that it has not only been designed for coding experts but for others also Page authors, Component writers etc. Because of integrating MVC model and flexible in its architecture JSF allows a wide range of users :

  1. 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.
  2. Application developers :
    Application developers can integrate this design with UI components. They program objects, event handling, converters, validators.
  3. 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.
  4. 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.
  5. 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.

  What are JSF releases?
JSF started its journey from version 1.0 and now it has come to its latest version JSF1.2. The listing of versions released so far is :

  1. JSF 1.2 (11 may 2006) -   Latest release of JSF specification.
  2. JSF 1.1 (27 may 2004) -   Bug fix release. No specification changes. No HTML renderkit changes.
  3. JSF 1.0 (11 mar 2004) -   Initial release of JSF specification.

There are many releases of 1.1 and 1.2 and these are listed below showing released date also:

  1. 1.2_04 P01  (20 Mar 2007)
  2. 1.2_04     (5 Mar 2007)
  3. 1.2_02   (25 Aug 2006)
  4. 1.2_01   (14 July 2006)
  5. 1.1_02   (24 Apr 2006)
  6. 1.1_01   (07 Sep 2004)

  How JSF Fits For Web Applications?
JSF has many  advantages over other existing frameworks that makes it a better choice for Java web application development. Some of the reasons are below:

  1. 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.
  2. 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.
  3. 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
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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 .
  9. 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. Java Server Faces adopts this property and let you specify which locale your application supports. So you can display you messages in different languages.
  10. 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

Part-3——————————————————————————————————————-

  1. What does component mean and what are its types?
    Components in JSF are elements like text box, button, table etc. that are used to create user interfaces of JSF Applications. These are objects that manage interaction with a user. 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. Components in JSF are of two types :
  1. Simple Components like text box, button and
  2. Compound Components like table, data grid etc.

A component containing many components inside it is called a compound component.

JSF allows you to create and use components of two types:

  1. Standard UI Components:
    JSF contains its basic set of  UI components like text box, check box, list boxe, button, label, radio button, table, panel etc. These are called standard components.
  2. 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.
  1. What are third party components and how they are useful?
    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 . These pre-built & enhanced components can be used in UI of your web application. For example, we are in need of a stylish calendar then we have an option to take it from third party rather than creating it our own. This will help saving time & cost creating effective & robust UI and to concentrate on business logic part of web application.
  2. What are tags in JSF ?
    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 (Sun Implementation) provides 43 tags in two standard JSF tag libraries:
  1. JSF Core Tags  Library
  2. JSF Html Tags Library

Even a very simple page uses tags from both libraries. These tags can be used adding the following lines of code at the head of the page.

<%@ taglib uri=?http://java.sun.com/jsf/core ? prefix=?f? %> (For Core Tags)
<%@ taglib uri=?http://java.sun.com/jsf/html ? prefix=?h? %> (For Html Tags)

  1. What is the difference between JSP and JSF?
    JSP simply provides a Page which may contain markup, embedded Java code, and tags which encapsulate more complicated logic / html.
    JSF may use JSP as its template, but provides much more. This includes validation, rich component model and lifecycle, more sophisticated EL, separation of data, navigation handling, different view technologies (instead of JSP), ability to provide more advanced features such as AJAX, etc

Part-4——————————————————————————————————————

  1. What is JSF life cycle and its phases?
    The series of steps followed by an application is called its life cycle. A JSF application typically follows six steps in its life.
  1. Restore view phase
  2. Apply request values phase
  3. Process validations phase
  4. Update model values phase
  5. Invoke application phase
  6. Render response phase
  1. What is the role of Renderer in JSF? and justify the statement “JSF supports multiple client devices”.
    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 be helpful. This is a simple task for JSF. The solution is to develop separate renderers for the component. JSF components use different renderers depending on the device used.
  2. What is Render Kit in JSF?
    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.
  3. What is conversion and validation? and how are they related?
    This is one of the phase of JSF life cycle that happens before binding the component data to the related backing bean in the Update model values phase. 
    Conversion is the process of transforming the component data from String to Java objects and vice versa. For example, an user enters a value (String) in an input component and this value is to store in a Date field in the backing bean then this String value is converted to a java.util.Date value when request is sent to the server and vice versa. This process is called Conversion.
    Validation is the process of ensuring data contains the expected content. For example, checking the Date value is in MM./dd/YYYY format or any integer value is between 1 to 10.
    The main purpose of conversion and validation is to ensure the values are of correct type and following the required criteria before updating model data. So this step allows you to focus on business logic rather than working on tedious qualifications of input data such as null checks, length qualifiers, range boundaries, etc.
  4. When automatic conversion is supplied by JSF Implementation?
    JSF implementation automatically converts component data between presentation view and model when the bean property associated with the component is of one of the types supported by the component’s data.
    For example, If a UISelectBoolean component is associated with a bean property of type Boolean, then JSF implementation will automatically convert the data from String to Boolean

Part-5————————————————————————————————————–

  Which type of converters can we use in our application?
A JSF application can use two types of converters :

  1. JSF standard Converters
    JSF supplies built-in converters known as standard converters. All standard converters implements javax.faces.convert.Converter interface. These converter classes are listed below :
  1. BigDecimalConverter
  2. BigIntegerConverter
  3. BooleanConverter
  4. ByteConverter
  5. CharacterConverter
  6. DateTimeConverter
  7. DoubleConverter
  8. FloatConverter
  9. IntegerConverter
  10. LongConverter
  11. NumberConverter
  12. ShortConverter
  • Custom Converter
    Custom data converter is useful in in converting field data into an application-specific value object. For example,
  1.  String to User object.
  2.  String to Product object  etc.

  Which standard converters have their own tags?
DateTimeConverter and NumberConverter are two standard converters that have their own tagsconvertDateTime and convertNumber respectively that help configuring the format of the component data by configuring tag attributes.
DateTimeConverter : A component data can be converted to a Date object using convertDateTime tag within the component tag like,

<h:inputText value=”#{Bean.RegisterDate}”>
<f:convertDateTime pattern=”MMM,dd,YYYY” />
</h:inputText>

NumberConverter : Converter for dealing with numbers such as type of number,  maximum integer digits, currency symbol etc.

<h:inputText id=”it” value=”#{Bean.value}”>
<f:convertNumber maxFractionDigits=”3″
type=”currency”
currencySymbol=”$”
maxIntegerDigits=”4″ />
</h:inputText>

  What are the ways of using standard converters of JSF?
Standard converters other than the two which have their own tags (DateTimeConverter and NumberConverter) can be used in one of the following three ways. The first one converts the model value of the component and the other two ways convert the component’s local value.

  1. Bind UI Component to Backing Bean Property :
    Make sure that the component has its value bound to a backing bean property of the same type as the converter. For example, converting component data to a float number requires binding the component to the property like :
Float value = 0.0;
public Float getValue(){ return value;}
public void setValue(Float value) {this.value = value;}
  1. Use ?converter? attribute on the UI Component :
    Using the converter attribute of the component tag. Just specify the fully qualified class name or ID of the converter in the converter attribute. If the component is not bound to a bean property then this option can be used. For example,
<h:inputText converter=”javax.faces.Integer” />
  1.  Use <f:converter> Tag with ConverterId Attribute :
    Using converter tag within the component tag and refer the converter by specifying the ID of the converter in the convertId attribute. For example:
<h:inputText value=”#{Bean.Value}” />
<f:converter converterId=”Float” />
</h:inputText>

Part-6——————————————————————————————————————

  When to create and use custom convertors?
The main reasons behind creating our converter are :

  1. When we want to convert a component’s data to a type other than a standard type
  2. When we want to convert the format of the data.

  What are the steps of creating and using custom converter in our application?
Creating and using a custom converter requires the following steps :

Steps to follow :

  1. Create a class that implements javax.faces.converter.Converter interface.
  2. Import necessary packages and classes.
  3. Implement two abstract methods “getAsObject()”, “getAsString()” provided byConverter interface. getAsObject() method converts the String (User Input) to Object andgetAsString() method converts the Object to String to send back to the page.
  4. Register the converter class in configuration file (faces-config.xml) adding <converter>element. This element has child elements <converter-id> (name of the converter to be used while programming )and <converter-class> ( name of the converter class which we have created).
  5. Create view page where <f:converter> tag is used with attribute “converterId” which specifies the name of the converter which we have specified in <converter-id> element of<converter> element in “faces-config.xml” file.
  6. Use <h:message> tag to display the error message.

  What are the ways to register the custom converters in faces context?
After creating custom converter class implementing Converter interface it needs to register in the faces context. This can be done in one of the two ways :

  1. Register the converter class with the id. This id is used in <f:convertrer> tag in our view page (For example, JSP).
<converter>
<converter-id>ms_Converter</converter-id>
<converter-class>ms_Converter</converter-class>
</converter>

Use this converter in the view page as :

<h:inputText id=”input_text”>
<f:converter  converterId=”ms_Converter” />
</h:inputText>
  1. Register the converter class to handle all “Email” objects, for example,  automatically.
<converter>  <converter-for-class>Email</converter-for-class>  <converter-class>EmailConverter</converter-class>
</converter>

If  we register the EmailConverter class to handle all Email objects automatically then there is no need to use the <f:converter/> tag in view page. Use this converter as :

<h:inputText id=”phone” value=”#{Bean.email}”>
</h:inputText>

 

Part-7——————————————————————————————————————-

  1. What is the use of immediate attribute?
    UIInput components and command components can set the immediate attribute to true. This attribute, when set to true, forces the conversion and validation phase to occur earlier in the lifecycle, during the apply request values phase.  In other words, if some components on the page have their immediate attributes set to true, then the validation, conversion, and events associated with these components will be processed during apply request values phase.

The immediate attribute can be used for the following purposes :

  1. Immediate attribute, when set to true, allows a commandLink or commandButton to process the back-end logic and ignore validation process related to the fields on the page. This allows navigation to occur even when there are validation errors.
  2. To make one or more input components “high priority” for validation, so validation is performed, if there is any invalid component data, only for high priority input components and not for low priority input components in the page. This helps reducing the number of error messages shown on the page.For example :
    In the code below, button performs navigation without validating the required field.
<h:inputText id=”it” required=”true”/>
<t:message for=”it”/>
<t:commandButton value=”submit” immediate=”true” action=”welcome”/>
  1. In the code below, validation is performed only for the first component when button is clicked in spite of being both the input components required.
<h:inputText id=”it1″ immediate=”true” required=”true”/>
<h:inputText id=”it2″ required=”true”/>
<t:message for=”it1″/>
<t:message for=”it2″/>
<t:commandButton value=”submit” action=”welcome”/>
  1. Explain the usage of immediate attribute in an application.
    Take an example of shopping cart application in which a page contain quantity fields for each product and two hyperlinks “Continue Shopping” and “Update quantities“. Now we have set the immediate attributes to “false” for all the quantity fields, “true” for “Continue Shopping” hyperlink and “false” for “Update quantities” hyperlink. If we click the “Continue Shopping” hyperlink, none of the changes entered into the quantity input fields will be processed. If you click the “Update Quantities” hyperlink, the values in the quantity fields will be updated in the shopping cart.
  2. How to get the error messages displayed?
    Error messages can be displayed using “message” and “messages” tag. “message” tag is used to display single error message for a particular component. The ID of the component for which the message is to be displayed is specified is specified in “for” attribute of the message tag.
    Error messages for all the components can be displayed at a place using “messages” tag. It supports two layouts “table” and “list“. List layout shows all the messages in a line and table layout places all the messages in a tabular format.
  3. How to avoid that all the messages are shown on the same line?
    messages” tag displays all error messages in a line because the default layout it supports is “list“. This tag also supplies one more value “table” for “layout” attribute which displays all error messages in a tabular format i.e. in subsequent lines. So specifying explicitly the value of “layout” attribute to “table” can solve the problem of displaying all messages in the same line

Part-8—————————————————————————————————————–

  1. How can we replace the JSF Standard Error Message?
    Create the message bundle file and set the value of the key for a particular type of error specified in JSF specification.
    For example, JSF specification supplies value “Value is required” for key “javax.faces.component.UIInput.REQUIRED” so replace the value in our message bundle file similar to the following :
 javax.faces.component.UIInput.REQUIRED= Please enter the required value.
  1. Register the message bundle within <application> tag  in the configuration file (faces-config.xml) and restart the server. Now when we use message or messages tag in the view page then the value specified in this message bundle file for a particular error is displayed.
  2. How we can change the appearance of error messages in a JSF Page?
    The appearance can be changed by any of the two methods :
    Using “style” attribute or “styleClass” attribute. “style” attribute is used to set the CSS style definition for the component while styleClass attribute is used to set the CSS class for the component. Using “styleClass” attribute is same as html “class” attribute.
  3. What is the significance of properties file (Resource Bundle) and how to use this in our JSF page?
    Properties file is a collection of param=value pairs. This provides a great benefit to the application like we can modify these values easily and there is no need to change the JSP file. For example, we can create “message.properties” like :
prompt=Enter Your Name:
greeting_text=Welcome In Roseindia
button_text=Submit
  1. Now edit the configuration file using <message-bundle> element which tells the application where the message resource file is located.
<application>
<message-bundle>roseindia.messages</message-bundle>
</application>
  1. Now, message resource bundle is loaded first using core tag <f:loadBundle> in view page. That loads the bundle and stores it in the request scope.
<f:loadBundle basename=”roseindia.messages” var=”message”/>
  1. We can now use this in our JSP like below :
<h:outputText value=”#{message.prompt}”/>
  1. How can I use several configuration resource files in one single application?
    JSF finds configuration file or files looking in context initialization parameter, javax.faces.CONFIG_FILES  in web.xml, that specifies one or more paths to multiple configuration files for your web application. These multiple paths must be comma separeted. The important point to remember is not to register /WEB-INF/faces-config.xml file in the web.xml. Otherwise, the JSF implementation will process it twice. For example, make changes in web.xml like below :
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>
/WEB-INF/test1-config.xml,/WEB-INF/test2-config.xml
</param-value>
</context-param>
  1.  Can we use a different configuration resource file in place of traditional “faces-config.xml” file in our application?
    JavaServer Faces technology provides an XML document for configuring resources. This file is used to register application’s resources, such as validators, converters, managed beans, and navigation rules. This application configuration resource file is usually called faces-config.xml. You can have more than one application configuration resource file but it must be valid against the DTD located at http://java.sun.com/dtd/web-facesconfig_1_0.dtd. Now register the file within context-param element in web.xml file

1.How To Configure JSF in ECLIPSE Click Below Link….

CONFIGURE- JSF-ECLIPSE

2.JSF App with MYSQL  Click Below Link….

JSF-MYSQL

 
Leave a comment

Posted by on 23/03/2012 in JSF

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: