Google News
logo
JSF Interview Questions
JSF (JavaServer Faces) is a server-side component-based user interface framework.

It is used to develop web applications. It provides a well-defined programming model and consists of rich API and tag libraries.

The latest version JSF 2 uses Facelets as its default templating system.
The features are :
 
* Java framework built over Servlet API
* UI components are stored on the server
* Event-driven programming model that is handled on the server
* Supports multiple client devices
* Ease of implementing 3rd party components
* Extensible architecture
* Extensive tool support from Borland, Exadel, Sun, Oracle, IBM, BEA, etc.
* Rapid application development (RAD) approach
* Supports internationalization of UI labels and text
The life cycle contains 6 phases :
 
1) Restore view : The life cycle begins with the restore view phase. When a link or button is clicked on the web page, a request is sent to JSF with operations as listed below:
 
 * View is built by JSF
 * Connects event handlers and validators to user interface components
 * Saves this View in FacesContext instance
 * Provides all information to FacesContext to process request

2) Apply request : Here, each component from the component tree is created. Use the decode method that captures and saves new values from request parameters. In case of any failure during conversion, it generates an error message and lists it on FacesContext. It will display validation messages or errors during the render response phase. JSF moves to render response phase when decode method event listeners call renderResponse method.
 
3) Process validation : During this phase, JSF processes component tree validators, examines attribute rules for validation, and compares them with the stored local value of the component. In case of invalid local value, JSF adds an error message to FacesContext instance, displaying the same page with an error message and with JSF life cycle moving further towards render response phase.
 
4) Model value update : After JSF verifies valid data, it sets the corresponding server-side object properties to the component’s local values and updates the bean properties, corresponding to the value attribute of the input component. When renderResponse from the current instance of FacesContext is being called by updateModels methods, JSF moves to the render response phase.
 
5) Invoke application : Application-level events like submitting form or forwarding to another page are being handled by Java Server Faces during this phase.
 
6) Render response : In case the application has JSP pages, JSF requests the application server to render the page, thereby adds components on the page to the component tree. Otherwise, an already built component tree need not add any components; JSP container move tags and renders components. The response state is saved after view content is rendered, making successive requests can access the state and its availability to restore view phase.
In the execute phase, when the first request is made, the application view is built or restored. For other subsequent requests other actions are performed like request parameter values are applied, conversions and validations are performed for component values, managed beans are updated with component values, and application logic is invoked.
Managed Beans are a Java class that consists of a set of getter/setter methods and properties. It acts as a model to the JSF framework and offers functionalities like,
 
* Component data validation
* Manage the execution of a component event
* Processing to decide what page application navigates next
* JSF use managed beans either by configuring them into an XML file or through annotations.

Following scopes are used for managed bean class :
 
* Application
* Session
* View
* Request
* None
* Custom
Managed Beans are Java beans that comprise getter and setter methods and have business logic designed in it. It may optionally have a backing bean. They act as a Model for UI components in the MVC framework.
 
For JSF 1.2, it is required to register them in the JSF configuration file, faces-config.xml, whereas, from JSF 2.0 onwards, annotations are used to register managed beans.
Facelets are lightweight page declaration language which uses HTML style templates to build component tree to build Java server faces views.
 
Some of Facelets feature are listed as below :
 
* It uses XHTML for creating web pages.
* Besides JSF and JSTL tag libraries, it offers Facelets tag libraries.
* Expression language support, component, and pages templating.
* Fast compile time
* High-performance rendering
* Extends its functionality to components and other server-side objects via customization
* Support for code reuse through composite components and templating
* Compile-time EL validation
Some of the Facelet tags used in JSF are listed below :
 
* ui: component defines the created component and adds to the component tree.
* ui: composition defines page composition, uses templates optionally, and ignores content outside.
* ui: debug defines debug component created and adds to the component tree.
* ui: decorate is similar to component tag, consider content outside this tag.
* ui: define is used to define content inserted into the page by a template.
* ui: fragment is similar to component and decorates tag. It considers content outside this tag.
* ui: include reuses and encapsulates multiple page content.
* ui: insert as name inserts contents into a template.
* ui: param pass parameters to the included file.
* ui: repeat an alternative for loop tags, like c: forEach or c: dataTable.
* ui: remove is used to remove content from a page.
The three types of text field tags are ;
 
<h:inputText> : This adds the text box next to the label field.
<h:inputSecret> : This type is used for password fields where the entered data is hidden.
<h:inputTextarea> : This type of fields is used while entering large number of characters.
The @ManagedProperty annotation allows you to inject one managed bin into another.
 
@ManagedProperty(value = “#{beanName}”)
private BeanName beanName;

 

The @ApplicationScoped annotation indicates that the managed bean will be available throughout the lifetime of the application.
JSF 1.0 :
* It is the first release of the JSF specifications
* Does not support the usage of annotations
* The API had a lot of bugs

JSF 2.0 :
* It is the second release of the JSF specifications
* JSF 2 supports the ajax features
* It is totally redesigned and used as an MVC framework.
The different JSF events existing are Action Events, Value Change Events, and Phase Events. The action events are a kind of handling UI button or click changes in the user interface modules or components. All the types of clicks can be handled in action events. The value change events can be any type of updating the values from UI page such as radio buttons, text fields, dropdowns etc. The Phase events are a kind of events where a triggered will be fired during either the start of the lifecycle phase or at the end of the lifecycle phase.
The JSF architecture contains different elements such as UI components which are presented as stateful objects on the server-side, builder or helper classes and its validators, navigation handlers and event handlers.

The application configuration and resource files for configuring the application resources to manage the JavaBeans components as models and its containing application-specific behavior or functionalities. The custom tags library is available for representing the event handlers & validators.

A custom tag library is also available for rendering the UI components. A Faces Servlet will exist to manage the Client requests and Server responses and also to manage the JSF view pages and managed beans and also a persistence framework in the behind to integrate with the database to the web application.
JavaServer Faces HTML tag library represents HTML form components and other basic HTML elements, which are used to display or accept data from the user. A JSF form sends this data to the server after submitting the form.
Value expression retrieves a value and sets a value. They are further divided into rvalue expression and lvalue expression. rvalue can only read data, whereas lvalue can read as well write data.
 
Public method of the bean is invoked by Method expression that returns the result required for validating the data component and event handling.
There are two types of validations in JSF namely, Declarative and Imperative.
 
Declarative Validations : The validations that are fired using JSF standard validators or Bean validators fall under declarative type.

Imperative validation : The standard validation messages would not be sufficient in all the cases and sometimes may require complex validations that are declared by the user overriding the standard validations and these are called Imperative validations.
The validator tags are listed below :
 
* f:validateLength : is used to validate string length.
* f:validateLongRange : is used while validating the numeric value range.
* f:validateDoubleRange : is used while validating float value range.
* f:validateRegex : validation compares given regular expression with JSF components.
JSF data table tags are used to display relational data in tabular format on JSF view pages.
 
Benefits offered by Data Table tags are :
 
* In order to display data, the data table can iterate over arrays or collection of values.
* Data Table tags offer attributes to modify its data that is displayed on the JSF view page.
JSF standard tag library consists of various HTML input types. Some of them are as listed below:
 
* h:inputText : Creates HTML text box of text type
* h:inputSecret : HTML text box of password type
* h:inputTextarea : HTML textarea input field
* h:inputHidden : HTML input of type hidden
* h:selectBooleanCheckbox : For single HTML check box
* h:selectManyCheckbox : For group of HTML check boxes
* h:selectOneRadio : For single HTML radio button
* h:selectOneListBox : For HTML single list box
The JSF <h: inputText> tag is used to render an input field on the web page.
 
It is used within a <h: form> tag to declare input field that allows the user to input data.
The JSF <h:outputText> is used to render a plain text.

If the "styleClass", "style", "dir" or "lang" attributes are present, render a "span" element.

If the "styleClass" attribute is present, render its value as the value of the "class" attribute.
The <h:form> tag represents an input form.

* It includes child components that can contain data which is either presented to the user or submitted with the form.

* It can also include HTML markup to lay out the components on the page.
The <h:commandButton>tag creates a submit button and used to submit an application form.
The <h:inputTextarea> tag renders an HTML "textarea" element.

* It allows a user to enter multiline string.
JSF renders it as an HTML "a" anchor element that acts as a form submit button when clicked. So, you can create an anchor tag by using this tag.

An <h:commandLink> tag must include a nested h:outputText tag, which represents the text that the user clicks to generate the event. It's also required to be placed inside a <h:form> tag.
It is a standard password field which accepts one line of text with no spaces and displays it as a set of asterisks as it is entered. In other words, we say, it is used to create an HTML password field which allows a user to input a string without the actual string appearing in the field.

<h:inputSecret value="#{user.password}" maxlength="15" size="14"   
required="true" requiredMessage="Password is required"></h:inputSecret>​

 

It renders an HTML "input" element of type hidden. It does not appear on the web page, so you can pass hidden information while submitting the form.

<h:inputHidden value="#{user.id}" id="userId" class="userId-class"></h:inputHidden>  
JSF renders it as an HTML element of type file. It is used to get the file as input. In HTML form, it allows a user to upload a file.

<h:inputFile  id="file-id"  value="#{user.fileName}" required="true"   
requiredMessage="Please upload a file" alt="upload file"></h:inputFile>

 

JSF renders an HTML element "img" tag. This tag is used to render an image on the web page.
 
<h:graphicImage id="image-id" name="user-image" url="#{user.fileLocation()}"   
height="50px" width="100px" alt="Image"></h:graphicImage>

 

It is used to display a single message for a particular component. You can display your custom message by passing the id of that component into the for the attribute.

* <h:message>
Tags for action and navigation commands include :
 
<h: commandButton> : generates an HTML button that confirms the form and thus allows you to start processing the data entered by the user.

<h: commandLink> : generates an HTML hyperlink equivalent to the HTML anchor tag. It can be associated with a managed bean or an Action class for handling events.
Yes, any number of faces configuration files can be used but should be declared in the web.xml file as shown below.
 
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="https://xmlns.jcp.org/xml/ns/javaee" 
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee 
	https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
	<param-name>javax.faces.CONFIG_FILES</param-name>
	<param-value>/WEB-INF/faces-config1.xml,/WEB-INF/faces-config2.xml</param-value>
</context-param>
</web-app>

 

* @ViewScoped : means that a managed bean exists over the lifetime of the JSF view (while the page is being shown).
 
* @SessionScoped : The bean will be available throughout the HTTP session.
 
* @CustomScoped : the bin will live for as long as it is in the Map, which is created to control the lifetime of the beans.
 
* @RequestScoped : The bean exists for the life of the request-response (HTTP request-response).
Backing Bean is a special JavaBean (java class) that collects values ​​from components, reacts to events, interacts with business logic. Associated with each component.
 
There may be several of them and the bin is not optional for the component’s UI, but simply uses it. Backing bean contains fields that will be populated from the component (it will add the values ​​entered by the user). The JSF component will not work with Java classes or with anything other than Backing bean.
* Validating a component's data
* Handling an event fired by a component
* Performs processing to determine the next page to which the application must navigate
Backing Beans should be defined in request scope whereas managed bean can be defined in request, session or application scopes. Backing bean is referenced by a form whereas a managed bean is registered with JSF and created automatically when needed.
The tag shows all the error messages at one place corresponding to UI elements. The “for” attribute can be used to represent the field for which error message has to be displayed.

In this section, we will see how to use the default JSF validators to shoot out the built in error messages to the users.

Some of the points to keep in mind before we write the xhtml file are :

The h:message tag is used to display all the error messages related to the UI components.
This h:message has the following attributes

* id attribute is the unique identifier for a ui component.
* style displays the style information like color,font etc
* for attribute describes the component name applicable for the form.

Let’s look in detail with an example as how to display the error messages
 
Create a JSF page named error.xhtml as error.xhtml

<h:message for="cname" style="color: red"></h:message>

The immediate attribute if set to true can force validations, events and conversions processed during request phase of the lifecycle. Command component’s immediate attribute indicates what happens when the component gets activated. If the button’s immediate attribute is set to true and associated text field’s immediate attribute set to false then the event is processed without applying the field’s value to the model. In other words the value entered in the field does not even reach the model when the button is clicked but immediately processed in the above scenario.
 
The rendered attribute indicates whether a component should be rendered or not in the view page. Rendered attribute can use arithmetic operators and literals with rvalue expression but not lvalue expressions.
There are two configuration files namely;
 
* web.xml : This is the general web application configuration file containing the details of deployment. This contains the faces config file responsible for handling the application.

* faces-config.xml : allows to configure the application, managed beans, converters, validators, and navigation.
Spring uses Inversion of Control and Dependency Injection whereas JSF does not.
 
* Spring has built in modules for Login-Logout available for ready integration whereas in JSF we have to write the login feature manually.
 
* Since Spring uses dependency injection the user based pojo classes can be injected with springs whereas JSF is tightly coupled with Java EE architecture.
In JSF when a button is clicked or change value in text filed etc then corresponding JSF component create an instance of the corresponding event class and adds the event to the event list. After adding the event in the event list JSF component call the corresponding listener or handler method.
 
Note : JSF also provides the facility to handle the application level events which happens when application start or stop.
JSF Events:
 
 
valueChangeListener : JSF fired value change events when user make changes in input components.
 
actionListener : JSF fired action events when user clicks on a button or link component.
 
Application Events : SF fired application events when application start or stop or during JSF lifecycle : PostConstructApplicationEvent, PreDestroyApplicationEvent, PreRenderViewEvent.
public String logout() {
  FacesContext fc = FacesContext.getCurrentInstance();
  HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
  session.invalidate();
  return "loginPage";
}

 

JSF provides a facility to place your resources at any section of your web page and render it to another section. You can relocate your resource by specifying the target attribute.
 
JSF Web Resources :
 
JSF web resources are the resources which are required for proper rendering in the web application. It includes images, script files, and any user-created component libraries.
 
JSF provides a standard way to store your web resources. You can use any one of the following to store your resources.
 
* It must be stored in a subdirectory of a resources directory at the web application root: resources/resource-identifier.

* A resource packaged in the web application's classpath must be in a subdirectory of the META-INF/resources directory within a web application : META-INF/resources/resource-identifier. You can use this file structure to package resources in a JAR file bundled in the web application.

The JavaServer Faces runtime will look for the resources in the preceding listed locations, in that order.