0% found this document useful (0 votes)
187 views

JSF Interview Questions and Answers

This document provides answers to common questions about Java Server Faces (JSF). It begins with an overview of JSF, including its advantages and available implementations. It then addresses questions about JSF navigation, memory scopes, managed beans, the expression language, lifecycle, and comparison to Struts. Specific topics covered include JSF tags, the difference between JSP and JSF, declaring message bundles, rendering, and accessing parameters from JSP pages.

Uploaded by

Deepak Bhagat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
187 views

JSF Interview Questions and Answers

This document provides answers to common questions about Java Server Faces (JSF). It begins with an overview of JSF, including its advantages and available implementations. It then addresses questions about JSF navigation, memory scopes, managed beans, the expression language, lifecycle, and comparison to Struts. Specific topics covered include JSF tags, the difference between JSP and JSF, declaring message bundles, rendering, and accessing parameters from JSP pages.

Uploaded by

Deepak Bhagat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

JAVA SERVER FACES (JSF)

Questions and Answers

Compiled by: Deepak Bhagat


Fusion Functional Consultant,
Solution Architect & ADF Trainer
Java Server Faces (JSF) Questions and Answers

Table of Contents
1 Overview ................................................................................................................. 1
2 Navigation ............................................................................................................... 6
3 Memory Scopes ....................................................................................................... 6
4 Managed Bean ......................................................................................................... 6
5 Expression Language ............................................................................................... 8
6 Events ..................................................................................................................... 8
7 Life Cycle................................................................................................................. 9
8 Comparison with Struts .......................................................................................... 10

i
ADF Essentials Training by Deepak Bhagat
Java Server Faces (JSF) Questions and Answers

1 Overview
1. What is JSF (or Java Server Faces)?
Java Server Faces (JSF) is an industry-standard and a framework for building component-based
user interfaces for web applications. JSF contains an API for representing UI components and
managing their state; handling events, server-side validation, and data conversion; defining page
navigation; supporting internationalization and accessibility, and providing extensibility for all
these features.

2. What are the advantages of JSF?


The major benefits of JavaServer Faces technology are:
JavaServer Faces architecture makes it easy for 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.
It offers a clean separation between behavior and presentation.
Provides a rich architecture for managing component state, processing component data,
validating user input, and handling events.
Robust event handling mechanism.
Events easily tied to server-side code.
Render kit support for different clients
Component-level control over statefulness
Highly 'pluggable' - components, view handler, etc
JSF also supports internationalization and accessibility
Offers multiple, standardized vendor implementations

3. What are the available implementations of JavaServer Faces?


The main implementations of JavaServer Faces are:
Reference Implementation (RI) by Oracle.
Apache MyFaces is an open-source JavaServer Faces (JSF) implementation or run-time.
ADF Faces is Oracle’s implementation for the JSF standard.

4. 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 (Oracle
Implementation) provides 43 tags in two standard JSF tag libraries:
JSF Core Tags Library.
JSF Html Tags Library.

5. What is the difference between JSP and JSF?


JSP simply provides a Page that may contain markup, embedded Java code, and tags that
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.

6. What Is a Java Server Faces Application?


Java Server 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.
1/11
ADF Essentials Training by Deepak Bhagat
Java Server Faces (JSF) Questions and Answers
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.

7. Explain what does a 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.

8. How to declare the Message Bundle in JSF?


We can declare the message bundle in two ways:
(Let’s assume com.brightwave.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.brightwave.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.brightwave.messages”
var=”message”/>

9. What does it mean by the rendering of a page in JSF?


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

10. 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.

11. How to print out HTML markup with h:outputText?


The h:outputText has an attribute escape that allows escaping 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 escaping.

2/11
ADF Essentials Training by Deepak Bhagat
Java Server Faces (JSF) Questions and Answers

12. How to add context path to URL for outputLink?


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”
>

13. How to access web.xml init parameters from the jsp page?
You can get it using initParam pre-defined JSF EL variable.
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']}”/>

14. 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.

15. How to show Confirmation Dialog when user Click the Command Link?
h:commandLink assign the onclick attribute for internal use. So, you cannot use it to write your
code. This problem will be fixed in 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>

16. What is the different between getRequestParameterMap() and


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

17. Explain what do you mean by a 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
3/11
ADF Essentials Training by Deepak Bhagat
Java Server Faces (JSF) Questions and Answers
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.

18. Can you explain some of the setbacks of JSF?


The main set back is having the business logic or data access logic in the getter methods.
Having too many rich components from third-party libraries like Richfaces, ICEFaces, etc. could
adversely impact performance due to bloated HTML pages.
Having too many backing beans in session scope could lead to memory and performance
issues.
Not coding in a thread-safe manner.
Not carefully designing the GUI and the relevant interactions

19. Explain the meaning of components in JSF and what are the different
types?
Components in JSF are objects that manage interaction with a user. Components help developers
to create UIs by assembling several components, associating them with object properties and
event handlers.
The different components in JSF are elements like text box, button, table, etc. that are used to
create user interfaces of JSF Applications. Once you have created a component, it’s simple to drop
that component onto any JSP. Components in JSF are of two types:
Simple Components like text box, button and Compound Components like a 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:
Standard UI Components: JSF contains its basic set of UI components like text box,
checkbox, list boxes, button, label, radio button, table, panel, etc. These are called standard
components.
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.

20. When is automatic conversion 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.

21. How does JSF depict the MVC (Model View Controller) model?
The data that is manipulated in form or the other is done by model. The data presented to the
user in one form or the other is done by the view. JSF has connected the view and the model.
The view can be depicted as shown by:
<h:inputText value="#{user.name}"/>
JSF acts as a 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 be triggered by the user on the Button press, which will invoke the
login Bean as stated in the faces-config.xml file. Hence, it could be summarized as below:
4/11
ADF Essentials Training by Deepak Bhagat
Java Server Faces (JSF) Questions and Answers

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 a specific page.

22. 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");

23. How to access web.xml init parameters from the jsp page?
You can get it using initParam pre-defined JSF EL variable.
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']}"/>

24. How to terminate the session?


To terminate the session, you can use the session invalidate method.
This is an example of 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(); %>

25. What is the domain object model?


The 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.

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

5/11
ADF Essentials Training by Deepak Bhagat
Java Server Faces (JSF) Questions and Answers
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. The 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.

2 Navigation
27. How to declare the page navigation in faces-config.xml file?
Navigation rules tell 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.

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


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

3 Memory Scopes
29. 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.

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


JSF supports three Bean Scopes.
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.

4 Managed Bean
31. 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.

32. What is Backing Bean?

6/11
ADF Essentials Training by Deepak Bhagat
Java Server Faces (JSF) Questions and Answers
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.

33. 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.

34. How to get the current page URL from backing bean?
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)

35. 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 A managed bean is a backing bean that has been registered with
that is referenced by a JSF (in faces-config.xml) and it automatically created (and
form. 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,

7/11
ADF Essentials Training by Deepak Bhagat
Java Server Faces (JSF) Questions and Answers

Backing Beans should be The managed beans that are created by JSF can be stored within
defined only in the request the request, session, or application scopes
scope

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.

5 Expression Language
36. What is the difference between JSP-EL and JSF-EL?
JSP-EL JSF-EL

In JSP-EL the value expressions are In JSF-EL the value expressions are delimited by
delimited by ${…}. #{…}.

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

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

6 Events
37. Explain the different types of JSF events?
JSF is an event-driven framework.
Action Events: bound to UI Command objects like a Command Button or a Hyperlink.
Whenever a user presses a Command Button or clicks a hyperlink these Events get
generated.
Value Change Events: bound to UI Components like Text Field, Check-Box, List and Radio
Buttons. The Value Change Event is fired as soon as the value that is displayed in the view
is modified.
Phase Events: As you saw earlier in the JSF overview blog, the request processing life-
cycle in JSF includes six phases and any JSF implementation will fire Phase events during
the start and end of each phase. If we want to capture the Phase Events, then we can define
a Phase Listener. These are handy for debugging as well.

38. Explain the way by which the events handled in JSF? What is the
difference between these event handling mechanisms?
Action handlers and event listeners provide an event-driven mechanism. Every time a user does
something like clicking a button, selecting an item from a drop-down, 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.

8/11
ADF Essentials Training by Deepak Bhagat
Java Server Faces (JSF) Questions and Answers
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 a FacesEvent as a parameter and
a void return type, while an action handler takes no parameters and returns a String.

39. How to reload the page after ValueChangeListener is invoked?


At the end of the ValueChangeListener, call
FacesContext.getCurrentInstance().renderResponse()

7 Life Cycle
40. What are the JSF lifecycle phases?
The six phases of the JSF application lifecycle are as follows (note the event processing at each
phase):
Restore view
Apply request values; process events
Process validations; process events
Update model values; process events
Invoke application; process events
Render response

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


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.
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.
Process validations: In this phase, each component will have its values validated against
the application's validation rules.
Update model values: In this phase, JSF updates the actual values of the server-side
model, by updating the properties of your backing beans.
Invoke application: In this phase, the JSF controller invokes the application to handle
Form submissions.
Render response: In this phase, JSF displays the view with all of its components in their
current state

9/11
ADF Essentials Training by Deepak Bhagat
Java Server Faces (JSF) Questions and Answers

8 Comparison with Struts


42. What are the differences between struts and JSF?
10/11
ADF Essentials Training by Deepak Bhagat
Java Server Faces (JSF) Questions and Answers
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. Besides, 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 include 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 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.

11/11
ADF Essentials Training by Deepak Bhagat

You might also like