Showing posts with label JSF. Show all posts
Showing posts with label JSF. Show all posts

JSF Interview questions

JSF Interview questions
Q: 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.
Q: 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 name login, and keep it alive for the duration of the request.
Q: 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”/>

Q: 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.

Q: What if no navigation rule matches a given action?
If no navigation rule matches a given action, then the current page is redisplayed.

Q: 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

Q: 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.

Q: 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.

Q: Is it possible to have more than one Faces Configuration file?
We can have any number of config files. Just need to register in web.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>

JSF Interview questions

JSF Interview questions
Q: 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.

Q: 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.

Q: 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.

Q: 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

Q: 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.
Q: 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.
Q: 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.
Q: 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.

JSF Interview questions

JSF Interview questions
Q: 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

Q: 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.


Q: 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.


Q: 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.


Q: 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.

JSF Interview questions

JSF Interview questions
Q: 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

Q: 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>

Q: 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"/>

Q: We can now use this in our JSP like below :
<h:outputText value="#{message.prompt}"/>
Q: 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>
Q: 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.


Q: 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.

JSF Interview questions

JSF Interview questions
Q: 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 :
a. 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.
b. 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"/>
c. 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"/>

Q: 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.

Q: 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.

Q: 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.

Q: 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.
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.

Q: 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.

JSF Interview questions

JSF Interview questions
Q: Which standard converters have their own tags?
DateTimeConverter and NumberConverter are two standard converters that have their own tags convertDateTime 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>

Q: 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>

Q: 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.
a. 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;}
b. 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" />
c.
d. 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>

Q: When to create and use custom convertors?
The main reasons behind creating our converter are :
a. When we want to convert a component's data to a type other than a standard type
b. When we want to convert the format of the data.
Read more at http://www.roseindia.net/jsf/customconverter.shtml

Q: 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 :
a. Create a class that implements javax.faces.converter.Converter interface.
b. Import necessary packages and classes.
c. Implement two abstract methods "getAsObject()", "getAsString()" provided by Converter interface. getAsObject() method converts the String (User Input) to Object and getAsString() method converts the Object to String to send back to the page.
d. 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).
e. 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.
f. Use <h:message> tag to display the error message.
Read more at http://www.roseindia.net/jsf/customconverter.shtml
Q: 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 :
a. 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>
b. Use this converter in the view page as :
<h:inputText id="input_text">
<f:converter converterId="ms_Converter" />
</h:inputText>
c.
d. 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>
e. 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>

JSF Interview questions

JSF Interview questions

Q: 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.
32. 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.
a. Restore view phase
b. Apply request values phase
c. Process validations phase
d. Update model values phase
e. Invoke application phase
f. Render response phase

Q: 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.


Q: 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.


Q: 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.


Q: 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.
1. 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
2. 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.

JSF Interview Questions

JSF Interview Questions

Q: How to print out html markup with h:outputText?
A: The h:outputText has attribute escape that allows to escape the html markup. By default, it equals to "true". It means all the special symbols will be replaced with '&' codes. If you set it to "false", the text will be printed out without ecsaping.
For example, <h:outputText value="<b>This is a text</b>"/>
will be printed out like:
<b>This is a text</b>
In case of <h:outputText escape="false" value="<b>This is a text</b>"/>
you will get:
This is a text

Q: h:inputSecret field becomes empty when page is reloaded. How to fix this?
A: Set redisplay=true, it is false by default.

Q: 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.


Q: 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 :
a. JSF 1.2 (11 may 2006) - Latest release of JSF specification.
b. JSF 1.1 (27 may 2004) - Bug fix release. No specification changes. No HTML renderkit changes.
c. 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:
d. 1.2_04 P01 (20 Mar 2007)
e. 1.2_04 (5 Mar 2007)
f. 1.2_02 (25 Aug 2006)
g. 1.2_01 (14 July 2006)
h. 1.1_02 (24 Apr 2006)
i. 1.1_01 (07 Sep 2004)


Q: 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:
a. 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.
b. 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.
c. 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
d. 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.
e. 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.
f. 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.
g. 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.
h. 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 .
i. 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.
j. 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.


Q: What does component mean and what are its types?
A: 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 :
a. Simple Components like text box, button and
b. 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)

JSF Interview Questions -

JSF Interview Questions -
Q: How does JSF depict the MVC (a.k.a Model View Controller) model?
Ans. The data that is manipulated in form or the other is done by model. The data presented to user in one form or the other is done by view. JSF is connects the view and the model. View can be depicted as shown by:
<h:inputText value="#{user.name}"/>
JSF acts as controller by way of action processing done by the user or triggering of an event. For ex.
<h:commandbutton value="Login" action="login"/>
, this button event will triggered by the user on Button press, which will invoke the login Bean as stated in the faces-config.xml file.
Hence, it could be summarized as below: User Button Click -> form submission to server -> invocation of Bean class -> result thrown by Bean class caught be navigation rule -> navigation rule based on action directs to specific page.

Q: What does it mean by rendering of page in JSF?
Ans. Every JSF page as described has various components made with the help of JSF library. JSF may contain h:form, h:inputText, h:commandButton, etc. Each of these are rendered (translated) to HTML output. This process is called encoding. The encoding procedure also assigns each component with a unique ID assigned by framework. The ID generated is random.

Q: How to show Confirmation Dialog when user Click the Command Link?
A: h:commandLink assign the onclick attribute for internal use. So, you cannot use it to write your own code. This problem will fixed in the JSF 1.2. For the current JSF version you can use onmousedown event that occurs before onclick. <script language="javascript"> function ConfirmDelete(link) { var delete = confirm('Do you want to Delete?'); if (delete == true) { link.onclick(); } } </script> . . . . <h:commandLink action="delete" onmousedown="return ConfirmDelete(this);"> <h:outputText value="delete it"/> </h:commandLink>

Q: What is the different between getRequestParameterMap() and getRequestParameterValuesMap()
getRequestParameterValuesMap() similar to getRequestParameterMap(), but contains multiple values for for the parameters with the same name. It is important if you one of the components such as <h:selectMany>.

Q: Is it possible to have more than one Faces Configuration file?
Yes. You can define the list of the configuration files in the web.xml.
This is an example:
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config-navigation.xml,/WEB-INF/faces-beans.xml</param-value>
</context-param>
Note: Do not register /WEB-INF/faces-config.xml file in the web.xml . Otherwise, the JSF implementation will process it twice.
________________________________________
Hi there, I guess the Note: column should have been meant or intended for "faces-config.xml" file as thats the default configuration file for JSF (which is similar to struts-config.xml for Struts!!). faces-context.xml file sounds like the user defined config file similar to the aforementioned two xml files.

Q: How to mask actual URL to the JSF page?
A: You'll need to implement your own version of javax.faces.ViewHandler which does what you need. Then, you register your own view handler in faces-config.xml.
Here's a simple abstract ViewHandler you can extend and then implement the 3 abstract methods for. The abstract methods you override here are where you'll do your conversions to/from URI to physical paths on the file system. This information is just passed right along to the default ViewHandler for JSF to deal with in the usual way. For example, you could override these methods to add and remove the file extension of an incoming view id (like in your example), for extension-less view URIs.
import java.io.IOException;
import java.util.Locale;
import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A facade view handler which maps URIs into actual physical views that the
* underlying implementation can deal with regularly.
*
* Therefore, all internal references to view ids, for example in faces-config,
* will use the path to the physical files. Everything publicized, however, will
* see a "converted" / facade url.
*/
public abstract class SimpleConverterViewHandler extends ViewHandler {
private static final Log LOG = LogFactory
.getLog(SimpleConverterViewHandler.class);
private final ViewHandler base;
public SimpleConverterViewHandler(ViewHandler base) {
this.base = base;
}
/**
* Distinguishes a URI from a physical file view.
*
* Tests if a view id is in the expected format -- the format corresponding
* to the physical file views, as opposed to the URIs.
*
* This test is necessary because JSF takes the view ID from the
* faces-config navigation, and calls renderView() on it, etc.
*/
public abstract boolean isViewFormat(FacesContext context, String viewId);
/**
* Convert a private file path (view id) into a public URI.
*/
public abstract String convertViewToURI(FacesContext context, String viewId);
/**
* Convert a public URI into a private file path (view id)
*
* note: uri always starts with "/";
*/
public abstract String convertURIToView(FacesContext context, String uri);
public String getActionURL(FacesContext context, String viewId) {
// NOTE: this is used for FORM actions.
String newViewId = convertViewToURI(context, viewId);
LOG.debug("getViewIdPath: " + viewId + "->" + newViewId);
return base.getActionURL(context, newViewId);
}
private String doConvertURIToView(FacesContext context, String requestURI) {
if (isViewFormat(context, requestURI)) {
return requestURI;
} else {
return convertURIToView(context, requestURI);
}
}
public void renderView(FacesContext context, UIViewRoot viewToRender)
throws IOException, FacesException {
if (null == context || null == viewToRender)
throw new NullPointerException("null context or view");
String requestURI = viewToRender.getViewId();
String newViewId = doConvertURIToView(context, requestURI);
LOG.debug("renderView: " + requestURI + "->" + newViewId);
viewToRender.setViewId(newViewId);
base.renderView(context, viewToRender);
}
public UIViewRoot restoreView(FacesContext context, String viewId) {
String newViewId = doConvertURIToView(context, viewId);
LOG.debug("restoreView: " + viewId + "->" + newViewId);
return base.restoreView(context, newViewId);
}
public Locale calculateLocale(FacesContext arg0) {
return base.calculateLocale(arg0);
}
public String calculateRenderKitId(FacesContext arg0) {
return base.calculateRenderKitId(arg0);
}
public UIViewRoot createView(FacesContext arg0, String arg1) {
return base.createView(arg0, arg1);
}
public String getResourceURL(FacesContext arg0, String arg1) {
return base.getResourceURL(arg0, arg1);
}
public void writeState(FacesContext arg0) throws IOException {
base.writeState(arg0);
}
}

JSF Interview Questions -

JSF Interview Questions -
Q: What is JSF architecture?
Ans. JSF was developed using MVC (a.k.a Model View Controller) design pattern so that applications can be scaled better with greater maintainability. It is driven by Java Community Process (JCP) and has become a standard. The advantage of JSF is that it’s both a Java Web user – interface and a framework that fits well with the MVC. It provides clean separation between presentation and behavior. UI (a.k.a User Interface) can be created by page author using reusable UI components and business logic part can be implemented using managed beans.

Q: How JSF different from conventional JSP / Servlet Model?
Ans. JSF much more plumbing that JSP developers have to implement by hand, such as page navigation and validation. One can think of JSP and servlets as the â€Å“assembly languageâ€? under the hood of the high-level JSF framework.

Q: How the components of JSF are rendered? An Example
Ans. In an application add the JSF libraries. Further in the .jsp page one has to add the tag library like:

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


Or one can try XML style as well:

<?xml version="1.0"?>
<jsp:root version="2.0"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">


Once this is done, one can access the JSF components using the prefix attached. If working with an IDE (a.k.a Integrated Development Environment) one can easily add JSF but when working without them one also has to update/make the faces-config.xml and have to populate the file with classes i.e. Managed Beans between
<faces-config> </faces-config> tags

Q: How to declare the Navigation Rules for JSF?
Ans. Navigation rules tells JSF implementation which page to send back to the browser after a form has been submitted. For ex. for a login page, after the login gets successful, it should go to Main page, else to return on the same login page, for that we have to code as:

<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/main.jsp<to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>fail</from-outcome>
<to-view-id>/login.jsp<to-view-id>
</navigation-case>
</navigation-rule>


from-outcome to be match with action attribute of the command button of the login.jsp as:
<h:commandbutton value="Login" action="login"/>

Secondly, it should also match with the navigation rule in face-config.xml as
<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>core.jsf.LoginBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>


In the UI component, to be declared / used as:
<h:inputText value="#{user.name}"/>

value attribute refers to name property of the user bean.
Q: How do I configure the configuration file?
Ans. The configuration file used is our old web.xml, if we use some IDE it will be pretty simple to generate but the contents will be something like below:

<?xml version=&quote;1.0&quote; encoding=&quote;UTF-8&quote;?>
<web-app version=&quote;2.4&quote; xmlns=&quote;http://java.sun.com/xml/ns/j2ee&quote; xmlns:xsi=&quote;http://www.w3.org/2001/XMLSchema-instance&quote; xsi:schemaLocation=&quote;http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quote;>
<context-param>
<param-name>com.sun.faces.verifyObjects</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.validateXml</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
</web-app>


The unique thing about this file is ?servlet mapping?. JSF pages are processed by a servlet known to be part of JSF implementation code. In the example above, it has extension of .faces. It would be wrong to point your browser to http://localhost:8080/MyJSF/login.jsp, but it has to be http://localhost:8080/MyJSF/login.faces. If you want that your pages to be with .jsf, it can be done with small modification :-) ,

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
<servlet-mapping>

Q: What is JSF framework?
Ans. JSF framework can be explained with the following diagram:

JSF interacts with Client Devices which ties together with presentation, navigation and event handling and business logic of web tier model. Hence JSF is limited to presentation logic / tier. For Database tier i.e. Database and Web services one has to rely on other services.

JSF Interview Questions -

JSF Interview Questions -
Q: How to terminate the session?
A: In order to terminate the session you can use session invalidate method.
This is an example how to terminate the session from the action method of a backing bean:

public String logout() {
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
session.invalidate();
return "login_page";
}
The following code snippet allows to terminate the session from the jsp page:
<% session.invalidate(); %> <c:redirect url="loginPage.jsf" />

Q: How to implement "Please, Wait..." page?
A: The client-side solution might be very simple. You can wrap the jsp page (or part of it you want to hide) into the DIV, then you can add one more DIV that appears when user clicks the submit button. This DIV can contain the animated gif you speak about or any other content.
Scenario: when user clicks the button, the JavaScript function is called. This function hides the page and shows the "Wait" DIV. You can customize the look-n-fill with CSS if you like.
This is a working example:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="demo.bundle.Messages" var="Message"/>

<html>
<head>
<title>Input Name Page</title>
<script>
function gowait() {
document.getElementById("main").style.visibility="hidden";
document.getElementById("wait").style.visibility="visible";
}
</script>

</head>
<body bgcolor="white">
<f:view>
<div id="main">
<h1><h:outputText value="#{Message.inputname_header}"/></h1>
<h:messages style="color: red"/>
<h:form id="helloForm">

<h:outputText value="#{Message.prompt}"/>
<h:inputText id="userName" value="#{GetNameBean.userName}" required="true">
<f:validateLength minimum="2" maximum="20"/>
</h:inputText>
<h:commandButton onclick="gowait()" id="submit"
action="#{GetNameBean.action}" value="Say Hello" />
</h:form>
</div>
<div id="wait" style="visibility:hidden; position: absolute; top: 0; left: 0">
<table width="100%" height ="300px">
<tr>
<td align="center" valign="middle">
<h2>Please, wait...</h2>
</td>
</tr>
</table>
</div>
</f:view>
</body>
</html>
If you want to have an animated gif of the "Wait" Page, the gif should be reloaded after the form is just submitted. So, assign the id for your image and then add reload code that will be called after some short delay. For the example above, it might be:
<script>
function gowait() {
document.getElementById("main").style.visibility="hidden";
document.getElementById("wait").style.visibility="visible";
window.setTimeout('showProgress()', 500);
}
function showProgress(){
var wg = document.getElementById("waitgif");
wg.src=wg.src;
}
</script>
....
....
....

<img id="waitgif" src="animated.gif">
Q: How to reload the page after ValueChangeListener is invoked?
A: At the end of the ValueChangeListener, call FacesContext.getCurrentInstance().renderResponse()

Q: How to download PDF file with JSF?
A: This is an code example how it can be done with action listener of the backing bean.
Add the following method to the backing bean:
public void viewPdf(ActionEvent event) {
String filename = "filename.pdf";
// use your own method that reads file to the byte array
byte[] pdf = getTheContentOfTheFile(filename);
FacesContext faces = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();
response.setContentType("application/pdf");
response.setContentLength(pdf.length);
response.setHeader( "Content-disposition", "inline; filename=\""+fileName+"\"");
try {
ServletOutputStream out;
out = response.getOutputStream();
out.write(pdf);
} catch (IOException e) {
e.printStackTrace();
}
faces.responseComplete();
}
This is a jsp file snippet:
<h:commandButton immediate="true" actionListener="#{backingBean.viewPdf}" value="Read PDF" />

Q: What is JSF?
Ans. JSF stands for Java Server Faces. JSF has set of pre-assembled User Interface (UI). By this it means complex components are pre-coded and can be used with ease. It is event-driven programming model. By that it means that JSF has all necessary code for event handling and component organization. Application programmers can concentrate on application logic rather sending effort on these issues. It has component model that enables third-party components to be added like AJAX.

Q: What is required for JSF to get started?
Ans. Following things required for JSF:
• JDK (Java SE Development Kit)
• JSF 1.2
• Application Server (Tomcat or any standard application server)
• Integrated Development Environment (IDE) Ex. Netbeans 5.5, Eclipse 3.2.x, etc.
Once JDK and Application Server is downloaded and configured, one can copy the JSF jar files to JSF project and could just start coding. :-)
If IDE is used, it will make things very smooth and will save your time.

JSF Interview Questions - home

JSF Interview Questions - home
Q: What is JavaServer Faces?
A: JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client. JSF provides ease-of-use in the following ways:

• Makes it easy to construct a UI from a set of reusable UI components
• Simplifies migration of application data to and from the UI
• Helps manage UI state across server requests
• Provides a simple model for wiring client-generated events to server-side application code
• Allows custom UI components to be easily built and re-used

Most importantly, JSF establishes standards which are designed to be leveraged by tools to provide a developer experience which is accessible to a wide variety of developer types, ranging from corporate developers to systems programmers. A "corporate developer" is characterized as an individual who is proficient in writing procedural code and business logic, but is not necessarily skilled in object-oriented programming. A "systems programmer" understands object-oriented fundamentals, including abstraction and designing for re-use. A corporate developer typically relies on tools for development, while a system programmer may define his or her tool as a text editor for writing code. Therefore, JSF is designed to be tooled, but also exposes the framework and programming model as APIs so that it can be used outside of tools, as is sometimes required by systems programmers.

Q: How to pass a parameter to the JSF application using the URL string?
A: if you have the following URL: http://your_server/your_app/product.jsf?id=777, you access the passing parameter id with the following lines of java code:

FacesContext fc = FacesContext.getCurrentInstance();
String id = (String) fc.getExternalContext().getRequestParameterMap().get("id");
From the page, you can access the same parameter using the predefined variable with name param. For example,
<h:outputText value="#{param['id']}" />
Note: You have to call the jsf page directly and using the servlet mapping.

Q: How to add context path to URL for outputLink?
A: Current JSF implementation does not add the context path for outputLink if the defined path starts with '/'. To correct this problem use #{facesContext.externalContext.requestContextPath} prefix at the beginning of the outputLink value attribute. For example:
<h:outputLink value="#{facesContext.externalContext.requestContextPath}/myPage.faces">
Q: How to get current page URL from backing bean?
A: You can get a reference to the HTTP request object via FacesContext like this:

FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
and then use the normal request methods to obtain path information. Alternatively,
context.getViewRoot().getViewId();
will return you the name of the current JSP (JSF view IDs are basically just JSP path names).

Q: How to access web.xml init parameters from java code?
You can get it using externalContext getInitParameter method. For example, if you have:
<context-param>
<param-name>connectionString</param-name>
<param-value>jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB</param-value>
</context-param>
You can access this connection string with:
FacesContext fc = FacesContext.getCurrentInstance();
String connection = fc.getExternalContext().getInitParameter("connectionString");

Q: How to access web.xml init parameters from jsp page?
You can get it using initParam pre-defined JSF EL valiable.
For example, if you have:
<context-param>
<param-name>productId</param-name>
<param-value>2004Q4</param-value>
</context-param>
You can access this parameter with #{initParam['productId']} . For example:
Product Id: <h:outputText value="#{initParam['productId']}"/>