1. What is JSF (or JavaServer Faces)?
Ans: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?
Ans: The major benefits of JavaServer Faces technology are:
3. What is Managed Bean?
Ans: 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.
4. What is Backing Bean?
Ans: 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.
5. What are the differences between a Backing Bean and Managed Bean?
Ans: 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.
6. 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.
Ans:
Backing Beans Managed Beans
A backing bean is any bean that is A managed bean is a backing bean that has been referenced by a form. 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 The managed beans that are created by JSF can
in the request scope 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.
6. What are the JSF life-cycle phases?
Ans: 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
7. 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.
8. What is the use of immediate attribute?
Ans: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 :
<t:message for="it"/>
<t:commandButton value="submit" immediate="true" action="welcome"/>
3. 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"/>
9.Explain the usage of immediate attribute in an application.
Ans: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.
10. What is differences between action and actionlistener in JSF components ? for example an command button has action and ActionListener properties , what is differences between them , when we should use each of them ?
Ans:
1. Basically the "action" attribute refers to an action method which returns a String from which the Faces navigation model can use to decide whether or not a navigation is necessary based on the value of the string.
typically one uses an action method to execute some code after a button or link is clicked and then possibly navigate based on the outcome of executed code.
An actionlistener method compared to an action method does not return a String. Instead it returns void. It is basically identical to the action method but instead it just executes the code after an action event (button click or link click) but a navigation is not needed.
A good example of actionlistener could be in response to clicking on a checkbox and having the actionlistener code behind it change a visual attribute of a page such as render a component that was not rendered before..
2. "In a nutshell, actions are designed for business logic and participate in navigation handling, whereas action listeners typically perform user interface logic and do not participate in navigation handling."
In theory since the action handlers don't need to reference any classes from the JSF framework, those method could be tested outside of the web container with JUnit for example, so it is good place to have your business logic.
3. Action Handlers and Event Listeners
Clicking a button, a hyperlink or changing a value in a form element normally requires an action of some type. Desktop GUI applications have for years provided a well defined model for event handling, JSF provides a similar mechanism. The primary distinction with JSF event handling is that the event is triggered on the client but handled on the server.
JSF provides two types of methods for handling events; listeners and action handlers, both of these may be defined within a managed bean. A listener takes an FacesEvent as a parameter and a void return type, while an action handler takes no parameters and returns a String. An advantage of using a listener is that the FacesEvent object provides additional information, such as the form element that initiated the event. An action handler in contrast has no knowledge of the source of the event but can, based upon its return value,initiate page navigation.
Action Handlers
Action handlers are generally used for page navigation. A common use is processing form post and navigating to a new page based upon some business logic. Page navigation is determined by the return value of the action handler and the navigation-rule specified in faces-config.xml.
Let’s look at an example…
In the above example a user populates the username and password form elements and presses the submit button (<h:commandButton>). The action attribute within <h:commandButton> identifies an actionHandler in the managedBean (submitButtonAction()) which, in this example, returns success. The navigation rule within faces-config.xml specifies that the user will now be directed to “home.jsf”; this assumes that FacesServlet is mapped to *.jsf in web.xml.
Event Listeners
When the user clicks a button or link, changes a value in a field, or makes a selection in a list, the application may need to react. JSF user interface components signal user actions by firing an event handled by application code that has registered itself to be notified of the event.
The two most commonly used event listeners are action and value-change, the others, data-model and phase will not be covered here. Listeners can be declared in a managed bean or in a separate listener class. Placing listeners in a separate class allows reuse across multiple page views. If creating a listener class the class must implement ActionListener or ValueChangeListener interfaces. As stated previously a listener takes a FacesEvent object its only parameter. The FacesEvent provides information about the event such as the form element that initiated the event and the phaseId related to the JSF life cycle phase. A FacesEvent has two sub interfaces, ActionEvent and ValueChangeEvent.
ActionEvent
The actionListener attribute is supported by the <h:commandButton> and <h:commandLink> components. Lets look at an example…
When the user presses the “Create User” button (<h:commandButton>) the JSF implementation will broadcast the event to any registered listeners; In this example the listener(submit_listener) in the createUser managed bean is executed. As an alternative to the actionListener attribute you may use an actionListener tag.
This code will invoke the method processAction on the action listener class ActionListenerImpl. ActionListenerImpl must implement the ActionListener interface, which defines the method processAction.
ValueChangeEvent
A ValueChangeEvent is useful whenever you want to be notified when there is a change in the value of a component, such as text modification in a text field or a check box selection. Most JSF components support the valueChangeListener attribute. Lets see an example…
When the user modifies text in the name form element (<h:inputText>) the JSF implementation will broadcast the event to any registered listeners; In this example the listener(nameChange_listener) in the createUser managed bean is executed. Notice that the ValueChangeEvent provides the original value of the component and its new (changed) value.
As an alternative to the valueChangeListener attribute the valueChangeListener tag may be used.
This code will invoke the method processValueChange on the action listener class ValueChangeListenerImpl. ValueChangeListenerImpl must implement the ValueChangeListener interface, which defines the method processValueChange.
Action handlers and event listeners are important features of JSF providing an event driven mechanism. Every time the user does something, such as clicking a button or submitting a form, an event occurs. Event notification is then sent via HTTP to the server and handled by the FacesServlet. Events can invoke custom business logic or initiate page navigation.
11)How do i get a component reference from method which is called through 'action' of a button or link???.... My need to do methodbinding to the component on call of action method..?
Ans: If the target component is bound back to the same managed bean (via the binding attribute), then it's available as an attribute of the object.
Or, you can get the view root from the FacesContext. Once you have the UIViewRoot, you can find the component using findComponent or invokeOnComponent
12) How do handle exception messages in JSF?
13)Validators and Converters
Ans: Java Server Faces provides the ability to both convert and validate user provided data to help ensure data integrity.
Conversion
Data conversion is the process of converting, or transforming, one data type into another. JSF will provide implicit conversion when you map a component’s value to a managed bean property of a Java primitive type or Object types of BigDecimal and BigInteger. Alternatively JSF provides a set of standard converters that may be explicitly specified using the converter attribute of a UIComponent tag. Let’s take a look at both the implicit and explicit conversion techniques.
Implicit conversion
Explicit conversion using the UIComponent converter attribute
JSF provides support for several standard conversion types.
· BigDecimal
· BigInteger
· Boolean
· Byte
· Character
· DateTime
· Double
· Float
· Integer
· Long
· Number
· Short
JSF also supplies converter tags that may be nested within a UIComponent.
DateTime and Number Converter tags
DateTime and Number converter tags supply attributes that may be used for additional data conversion precision.
DateTime Converter
This is my favorite converter with several options that make, the often
painful, job of date conversion so much easier. Lets take a look at the list of attributes and their values.
· dateStyle
o default – Jan 1, 2006 1:20:45 PM
o short – 1/1/06 1:20:45 PM
o medium - Jan 1, 2006 1:20:45 PM
o long - January 1, 2006 1:20:45 PM
o full - Sunday, January 1, 2006 1:20:45 PM
· locale
o java.util.Locale(String language, String country)
o Locale.SPAIN, Locale.CANADA, etc.
· pattern
o Java.text.SimpleDateFormat
o yyyy.MM.dd ‘at’ HH:mm:ss z – 2007.01.01 at 12:05:30 PDT
o EEE, MMM d ‘yy - Mon, Jan 1, ’07
o h:mm a – 10:05 AM
o hh ‘o’ ‘clock’ a, zzzz - 12 o’ clock PM, Pacific Daylight Time
· timeStyle
o default – Jan 1, 2007 10:05:30 AM
o short - 1/1/07 10:05:30 AM
o medium - Jan 1, 2006 10:05:30 AM
o long - January 1, 2007 10:05:30 AM
o full - Monday, January 1, 2006 10:05:30 AM
· timeZone
o java.util.TimeZone
· type
o both Date and time.
o date Date only.
o time Time only.
Here is a simple output-text example of a convertDateTime tag…
Now lets look at an input-text example…
User input must be in the “MM/dd/yyyy” format, otherwise they will receive an error stating such. The JSF implementation will convert the input from a String into a java.util.Date.
Number Converter
Number converters are excellent for formatting the display of numeric data.
Lets take a look at the standard converters and their attributes.
· currencyCode
o The ISO 4217 currency code, applied only when formatting currencies. A
three-letter codes such as “USD” for the United States Dollar, “GBP” for the United Kingdom Pound, and “EUR” for the Euro. I found that not all codes listed in ISO 4217 were implemented.
· currencySymbol
o Currency symbol, is applied only when formatting currencies. If the currency
code is set then currencySymbol will be ignored. This is the literal currency symbol, such as “$”.
· groupingUsed
o Flag specifying whether formatted output will contain grouping separators. Default value is true.
· integerOnly
o Flag specifying whether only the integer part of the value will be formatted and parsed. Default value is false.
· maxFractionDigits
o Maximum number of digits that will be formatted in the fractional portion of the output.
· maxIntegerDigits
o Maximum number of digits that will be formatted in the integer portion of the output.
· minFractionDigits
o Minimum number of digits that will be formatted in the fractional portion of the output.
· minIntegerDigits
o Minimum number of digits that will be formatted in the integer portion of the output.
· locale
o A java.util.Locale used to define a language and country. If not specified, the Locale returned by FacesContext.getViewRoot().getLocale() will be used.
· pattern
o Custom formatting pattern which determines how the number string should be formatted and parsed.
Examples…
o ###,### – 123,456
o $###,###.## - $123,456.99
o #.### – 1.789
· type
o Specifies the number type. Valid values are “number”, “currency”, and “percent”. Default value is “number”.
In this currency example we use the locale attribute to format a currency value. The locale attribute is very helpful when supporting internalization.
Custom converters
If the standard converters do not fulfill yours needs then you may want to create your own. There are several steps to creating a custom converter including…
1. Create a converter class that implements the “javax.faces.convert.Converter” interface.
2. Implement the getAsObject() and getAsString() methods within your converter class.
3. Register your converter in faces-config.xml.
4. Use the <f:converter> tag in your page view.
This example is a custom converter that formats an SSN by inserting ‘-’ separators for output display, and stripping the ‘-’ separators when retrieving the SSN from UIInput component.
Validators
Validators can be specified using a component’s validator attribute or by nesting JSF provided tags. Validation can be performed only on UIInput components or components whose classes extend UIInput. Using the validator attribute of a UIInput component allows you to specify a custom validator or a validate method on a managedBean.
When using the standard Validator implementations, you don’t need to write any code to perform validation. You simply nest the standard validator tag of your choice inside a tag that represents a component of type UIInput (or a subclass of UIInput) and provide the necessary constraints. Let’s look at the JSF supplied standard validators.
· LengthValidator - Checks whether the length of a component’s value is within a certain range. This validator counts the number of characters.
o Minimum – The minimum acceptable number of characters.
o Maximum – The maximum acceptable number of characters.
· LongRangeValidator - Checks whether the value of a component is within a certain range. The validator will attempt to convert the number to a Java long primitive. If minimum and maximum attributes are used the validator will ensure that the value entered is within the minimum and maximum range. If the minimum and maximum attribute are omitted then the validator ensures that the value is numeric.
o Minimum – The minimum acceptable numeric value.
o Maximum – The maximum acceptable numeric value.
· DoubleRangeValidator - Checks whether the value of a component is within a certain range. The value must be numeric or convertible to a numeric value. The
validator will attempt to convert the number into a Java double primitive. If minimum and maximum attributes are used the validator will ensure that the value entered is within the minimum and maximum range. If the minimum and maximum attribute are omitted then the validator only ensures that the value is numeric.
o Minimum – The minimum acceptable numeric value.
o Maximum – The maximum acceptable numeric value.
LengthValidator
LongRangeValidator
DoubleRangeValidator
Custom ManagedBean Validator
You may place a custom validator method within a managedBean and bind it
to the validator attribute of any UIInput component. When adding a validator to a managed bean the validator method must accept
(FacesContext context, UIComponent toValidate, Object value) as method parameters.
Custom Validator
JSF makes it very easy to create a custom validator class and tag. Your custom validator class must implement the javax.faces.validator.Validator interface which will require a validate method. Next you will need to register your validator in faces-config.
Requiring a Value
If a UIInput component does not have the required attribute set to “true” and the user does not enter a value, then the validator will not be called. Remember to set required=”true”, if you want to force validation.
Ans: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?
Ans: 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 is Managed Bean?
Ans: 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.
4. What is Backing Bean?
Ans: 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.
5. What are the differences between a Backing Bean and Managed Bean?
Ans: 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.
6. 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.
Ans:
Backing Beans Managed Beans
A backing bean is any bean that is A managed bean is a backing bean that has been referenced by a form. 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 The managed beans that are created by JSF can
in the request scope 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.
6. What are the JSF life-cycle phases?
Ans: 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
7. 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.
8. What is the use of immediate attribute?
Ans: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 :
- 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.
- 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.
<t:message for="it"/>
<t:commandButton value="submit" immediate="true" action="welcome"/>
3. 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"/>
9.Explain the usage of immediate attribute in an application.
Ans: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.
10. What is differences between action and actionlistener in JSF components ? for example an command button has action and ActionListener properties , what is differences between them , when we should use each of them ?
Ans:
1. Basically the "action" attribute refers to an action method which returns a String from which the Faces navigation model can use to decide whether or not a navigation is necessary based on the value of the string.
typically one uses an action method to execute some code after a button or link is clicked and then possibly navigate based on the outcome of executed code.
An actionlistener method compared to an action method does not return a String. Instead it returns void. It is basically identical to the action method but instead it just executes the code after an action event (button click or link click) but a navigation is not needed.
A good example of actionlistener could be in response to clicking on a checkbox and having the actionlistener code behind it change a visual attribute of a page such as render a component that was not rendered before..
2. "In a nutshell, actions are designed for business logic and participate in navigation handling, whereas action listeners typically perform user interface logic and do not participate in navigation handling."
In theory since the action handlers don't need to reference any classes from the JSF framework, those method could be tested outside of the web container with JUnit for example, so it is good place to have your business logic.
3. Action Handlers and Event Listeners
Clicking a button, a hyperlink or changing a value in a form element normally requires an action of some type. Desktop GUI applications have for years provided a well defined model for event handling, JSF provides a similar mechanism. The primary distinction with JSF event handling is that the event is triggered on the client but handled on the server.
JSF provides two types of methods for handling events; listeners and action handlers, both of these may be defined within a managed bean. A listener takes an FacesEvent as a parameter and a void return type, while an action handler takes no parameters and returns a String. An advantage of using a listener is that the FacesEvent object provides additional information, such as the form element that initiated the event. An action handler in contrast has no knowledge of the source of the event but can, based upon its return value,initiate page navigation.
Action Handlers
Action handlers are generally used for page navigation. A common use is processing form post and navigating to a new page based upon some business logic. Page navigation is determined by the return value of the action handler and the navigation-rule specified in faces-config.xml.
Let’s look at an example…
In the above example a user populates the username and password form elements and presses the submit button (<h:commandButton>). The action attribute within <h:commandButton> identifies an actionHandler in the managedBean (submitButtonAction()) which, in this example, returns success. The navigation rule within faces-config.xml specifies that the user will now be directed to “home.jsf”; this assumes that FacesServlet is mapped to *.jsf in web.xml.
Event Listeners
When the user clicks a button or link, changes a value in a field, or makes a selection in a list, the application may need to react. JSF user interface components signal user actions by firing an event handled by application code that has registered itself to be notified of the event.
The two most commonly used event listeners are action and value-change, the others, data-model and phase will not be covered here. Listeners can be declared in a managed bean or in a separate listener class. Placing listeners in a separate class allows reuse across multiple page views. If creating a listener class the class must implement ActionListener or ValueChangeListener interfaces. As stated previously a listener takes a FacesEvent object its only parameter. The FacesEvent provides information about the event such as the form element that initiated the event and the phaseId related to the JSF life cycle phase. A FacesEvent has two sub interfaces, ActionEvent and ValueChangeEvent.
ActionEvent
The actionListener attribute is supported by the <h:commandButton> and <h:commandLink> components. Lets look at an example…
When the user presses the “Create User” button (<h:commandButton>) the JSF implementation will broadcast the event to any registered listeners; In this example the listener(submit_listener) in the createUser managed bean is executed. As an alternative to the actionListener attribute you may use an actionListener tag.
This code will invoke the method processAction on the action listener class ActionListenerImpl. ActionListenerImpl must implement the ActionListener interface, which defines the method processAction.
ValueChangeEvent
A ValueChangeEvent is useful whenever you want to be notified when there is a change in the value of a component, such as text modification in a text field or a check box selection. Most JSF components support the valueChangeListener attribute. Lets see an example…
When the user modifies text in the name form element (<h:inputText>) the JSF implementation will broadcast the event to any registered listeners; In this example the listener(nameChange_listener) in the createUser managed bean is executed. Notice that the ValueChangeEvent provides the original value of the component and its new (changed) value.
As an alternative to the valueChangeListener attribute the valueChangeListener tag may be used.
This code will invoke the method processValueChange on the action listener class ValueChangeListenerImpl. ValueChangeListenerImpl must implement the ValueChangeListener interface, which defines the method processValueChange.
Action handlers and event listeners are important features of JSF providing an event driven mechanism. Every time the user does something, such as clicking a button or submitting a form, an event occurs. Event notification is then sent via HTTP to the server and handled by the FacesServlet. Events can invoke custom business logic or initiate page navigation.
11)How do i get a component reference from method which is called through 'action' of a button or link???.... My need to do methodbinding to the component on call of action method..?
Ans: If the target component is bound back to the same managed bean (via the binding attribute), then it's available as an attribute of the object.
Or, you can get the view root from the FacesContext. Once you have the UIViewRoot, you can find the component using findComponent or invokeOnComponent
12) How do handle exception messages in JSF?
13)Validators and Converters
Ans: Java Server Faces provides the ability to both convert and validate user provided data to help ensure data integrity.
Conversion
Data conversion is the process of converting, or transforming, one data type into another. JSF will provide implicit conversion when you map a component’s value to a managed bean property of a Java primitive type or Object types of BigDecimal and BigInteger. Alternatively JSF provides a set of standard converters that may be explicitly specified using the converter attribute of a UIComponent tag. Let’s take a look at both the implicit and explicit conversion techniques.
Implicit conversion
Explicit conversion using the UIComponent converter attribute
JSF provides support for several standard conversion types.
· BigDecimal
· BigInteger
· Boolean
· Byte
· Character
· DateTime
· Double
· Float
· Integer
· Long
· Number
· Short
JSF also supplies converter tags that may be nested within a UIComponent.
DateTime and Number Converter tags
DateTime and Number converter tags supply attributes that may be used for additional data conversion precision.
DateTime Converter
This is my favorite converter with several options that make, the often
painful, job of date conversion so much easier. Lets take a look at the list of attributes and their values.
· dateStyle
o default – Jan 1, 2006 1:20:45 PM
o short – 1/1/06 1:20:45 PM
o medium - Jan 1, 2006 1:20:45 PM
o long - January 1, 2006 1:20:45 PM
o full - Sunday, January 1, 2006 1:20:45 PM
· locale
o java.util.Locale(String language, String country)
o Locale.SPAIN, Locale.CANADA, etc.
· pattern
o Java.text.SimpleDateFormat
o yyyy.MM.dd ‘at’ HH:mm:ss z – 2007.01.01 at 12:05:30 PDT
o EEE, MMM d ‘yy - Mon, Jan 1, ’07
o h:mm a – 10:05 AM
o hh ‘o’ ‘clock’ a, zzzz - 12 o’ clock PM, Pacific Daylight Time
· timeStyle
o default – Jan 1, 2007 10:05:30 AM
o short - 1/1/07 10:05:30 AM
o medium - Jan 1, 2006 10:05:30 AM
o long - January 1, 2007 10:05:30 AM
o full - Monday, January 1, 2006 10:05:30 AM
· timeZone
o java.util.TimeZone
· type
o both Date and time.
o date Date only.
o time Time only.
Here is a simple output-text example of a convertDateTime tag…
Now lets look at an input-text example…
User input must be in the “MM/dd/yyyy” format, otherwise they will receive an error stating such. The JSF implementation will convert the input from a String into a java.util.Date.
Number Converter
Number converters are excellent for formatting the display of numeric data.
Lets take a look at the standard converters and their attributes.
· currencyCode
o The ISO 4217 currency code, applied only when formatting currencies. A
three-letter codes such as “USD” for the United States Dollar, “GBP” for the United Kingdom Pound, and “EUR” for the Euro. I found that not all codes listed in ISO 4217 were implemented.
· currencySymbol
o Currency symbol, is applied only when formatting currencies. If the currency
code is set then currencySymbol will be ignored. This is the literal currency symbol, such as “$”.
· groupingUsed
o Flag specifying whether formatted output will contain grouping separators. Default value is true.
· integerOnly
o Flag specifying whether only the integer part of the value will be formatted and parsed. Default value is false.
· maxFractionDigits
o Maximum number of digits that will be formatted in the fractional portion of the output.
· maxIntegerDigits
o Maximum number of digits that will be formatted in the integer portion of the output.
· minFractionDigits
o Minimum number of digits that will be formatted in the fractional portion of the output.
· minIntegerDigits
o Minimum number of digits that will be formatted in the integer portion of the output.
· locale
o A java.util.Locale used to define a language and country. If not specified, the Locale returned by FacesContext.getViewRoot().getLocale() will be used.
· pattern
o Custom formatting pattern which determines how the number string should be formatted and parsed.
Examples…
o ###,### – 123,456
o $###,###.## - $123,456.99
o #.### – 1.789
· type
o Specifies the number type. Valid values are “number”, “currency”, and “percent”. Default value is “number”.
In this currency example we use the locale attribute to format a currency value. The locale attribute is very helpful when supporting internalization.
Custom converters
If the standard converters do not fulfill yours needs then you may want to create your own. There are several steps to creating a custom converter including…
1. Create a converter class that implements the “javax.faces.convert.Converter” interface.
2. Implement the getAsObject() and getAsString() methods within your converter class.
3. Register your converter in faces-config.xml.
4. Use the <f:converter> tag in your page view.
This example is a custom converter that formats an SSN by inserting ‘-’ separators for output display, and stripping the ‘-’ separators when retrieving the SSN from UIInput component.
Validators
Validators can be specified using a component’s validator attribute or by nesting JSF provided tags. Validation can be performed only on UIInput components or components whose classes extend UIInput. Using the validator attribute of a UIInput component allows you to specify a custom validator or a validate method on a managedBean.
When using the standard Validator implementations, you don’t need to write any code to perform validation. You simply nest the standard validator tag of your choice inside a tag that represents a component of type UIInput (or a subclass of UIInput) and provide the necessary constraints. Let’s look at the JSF supplied standard validators.
· LengthValidator - Checks whether the length of a component’s value is within a certain range. This validator counts the number of characters.
o Minimum – The minimum acceptable number of characters.
o Maximum – The maximum acceptable number of characters.
· LongRangeValidator - Checks whether the value of a component is within a certain range. The validator will attempt to convert the number to a Java long primitive. If minimum and maximum attributes are used the validator will ensure that the value entered is within the minimum and maximum range. If the minimum and maximum attribute are omitted then the validator ensures that the value is numeric.
o Minimum – The minimum acceptable numeric value.
o Maximum – The maximum acceptable numeric value.
· DoubleRangeValidator - Checks whether the value of a component is within a certain range. The value must be numeric or convertible to a numeric value. The
validator will attempt to convert the number into a Java double primitive. If minimum and maximum attributes are used the validator will ensure that the value entered is within the minimum and maximum range. If the minimum and maximum attribute are omitted then the validator only ensures that the value is numeric.
o Minimum – The minimum acceptable numeric value.
o Maximum – The maximum acceptable numeric value.
LengthValidator
LongRangeValidator
DoubleRangeValidator
Custom ManagedBean Validator
You may place a custom validator method within a managedBean and bind it
to the validator attribute of any UIInput component. When adding a validator to a managed bean the validator method must accept
(FacesContext context, UIComponent toValidate, Object value) as method parameters.
Custom Validator
JSF makes it very easy to create a custom validator class and tag. Your custom validator class must implement the javax.faces.validator.Validator interface which will require a validate method. Next you will need to register your validator in faces-config.
Requiring a Value
If a UIInput component does not have the required attribute set to “true” and the user does not enter a value, then the validator will not be called. Remember to set required=”true”, if you want to force validation.