Wednesday, November 20, 2013


JSF Interview Questions

February 13, 2009 by Krishna Srinivasan 9 Comments


1) What is JSF?

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. If you are interested in reading specific articles about Java Server Faces (JSF),
also read:

2) What is required for JSF to get started?

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.

3) What is JSF architecture?

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.

4) How JSF different from conventional JSP / Servlet Model?

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.

5) How the components of JSF are rendered? An Example

In an application add the JSF libraries. Further in the .jsp page one has to add the tag library like:
1
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
2
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
Or one can try XML style as well:
1
"1.0"?>
2
"2.0" xmlns:jsp="http://java.sun.com/JSP/Page"
3
4
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
1
tags

6) How to declare the Navigation Rules for JSF?

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:
1
2
/login.jsp
3
case>
4
login
5
/main.jsp
6

case>
7
case>
8
fail
9
/login.jsp
10
case>
11
from-outcome to be match with action attribute of the command button of the login.jsp as:
1
"Login" action="login"/>
Secondly, it should also match with the navigation rule in face-config.xml as
1
2
user
3
class>core.jsf.LoginBean
class>
4
session
5
In the UI component, to be declared / used as:
1
"#{user.name}"/>
value attribute refers to name property of the user bean.

7) How do I configure the configuration file?

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:
1
"e;1.0"e; encoding="e;UTF-8"e;?>
2

3
"e;2.4"e;
4
            xmlns="e;http://java.sun.com/xml/ns/j2ee"e;
5
6
xsi:schemaLocation="e;http://java.sun.com/xml/ns/j2ee
7

8
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"e;>
9

10
11
com.sun.faces.verifyObjects
12
false

13
14

15
16
com.sun.faces.validateXml
17
true
18
19

20
21
javax.faces.STATE_SAVING_METHOD
22
client
23
24

25
26
Faces Servlet
27
class>
28
               javax.faces.webapp.FacesServlet
29
        
class>
30
1
31
32

33
34
Faces Servlet
35
/faces/*
36
37

38
39
40
30
41
42
43

44
45
46
index.jsp
47
48
49
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 :-) ,
1
2
Faces Servlet
3
*.jsf
4

5

8)What is JSF framework?

JSF framework can be explained with the following diagram:
As can be seen in Figure 1, 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.

9) How does JSF depict the MVC (a.k.a Model View Controller) model?

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:
1
"#{user.name}"/>
JSF acts as controller by way of action processing done by the user or triggering of an event. For ex.
1
"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.

10) What does it mean by rendering of page in JSF?

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.

11) What is JavaServer Faces?

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.

12) How to pass a parameter to the JSF application using the URL string?

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

13) 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:
1
2
value="#{facesContext.externalContext.requestContextPath}/myPage.faces">

14) How to get current page URL from backing bean?

You can get a reference to the HTTP request object via FacesContext like this:
1
FacesContext fc = FacesContext.getCurrentInstance();
2
HttpServletRequest request = (HttpServletRequest)
3
fc.getExternalContext().getRequest();
and then use the normal request methods to obtain path information. Alternatively,
1
context.getViewRoot().getViewId();
will return you the name of the current JSP (JSF view IDs are basically just JSP path names).

15) How to access web.xml init parameters from java code?

You can get it using externalContext getInitParameter method. For example, if you have:
1
2
connectionString
3
4
jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB
5

6
You can access this connection string with:
1
FacesContext fc = FacesContext.getCurrentInstance();
2
String connection = fc.getExternalContext()
3
.getInitParameter("connectionString");

16) 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:
1
2
productId
3
2004Q4
4

You can access this parameter with #{initParam['productId']} . For example:
1
Product Id: "#{initParam['productId']}"/>

17) How to terminate the session?

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:
1
public String logout() {
2
FacesContext fc = FacesContext.getCurrentInstance();
3
HttpSession session = (HttpSession) fc
4
.getExternalContext().getSession(false);
5
session.invalidate();
6
return "login_page";
7
}
The following code snippet allows to terminate the session from the jsp page:
1
<% session.invalidate(); %> "loginPage.jsf" />

18) How to implement “Please, Wait…” page?

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:
1
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
2
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
3
"demo.bundle.Messages" var="Message"/>
4

5
6
7
Input Name Page
8
14

15

16
"white">
17
18
"main">
19

20
value="#{Message.inputname_header}"/>
21
"color: red"/>
22
"helloForm">
23
"#{Message.prompt}"/>
24
"userName"
25
value="#{GetNameBean.userName}" required="true">
26
"2" maximum="20"/>
27
28
"gowait()"
29
id="submit" action="#{GetNameBean.action}"
30
value="Say Hello" />
31
32
33
"wait" style="visibility:hidden;
34
position: absolute; top: 0; left: 0">
35
"100%" height ="300px">
36
"center" valign="middle">
37
38

Please, wait...

39
40
41
42
43
44
45
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:
1
12
....
13
....
14
....
15

16
"waitgif" src="animated.gif">

19) How to reload the page after ValueChangeListener is invoked?

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

20) How to download PDF file with JSF?

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:
1
public void viewPdf(ActionEvent event) {
2
String filename = "filename.pdf";
3

4
// use your own method that reads file to the byte array
5
byte[] pdf = getTheContentOfTheFile(filename);
6

7
FacesContext faces = FacesContext.getCurrentInstance();
8
HttpServletResponse response = (HttpServletResponse)
9
faces.getExternalContext().getResponse();
10
response.setContentType("application/pdf");
11
response.setContentLength(pdf.length);
12
response.setHeader( "Content-disposition",
13
"inline; filename=\""+fileName+"\"");
14
try {
15
ServletOutputStream out;
16
out = response.getOutputStream();
17
out.write(pdf);
18
catch (IOException e) {
19
e.printStackTrace();
20
}
21
faces.responseComplete();
22
}
This is a jsp file snippet:
1
"true"
2
  actionListener="#{backingBean.viewPdf}"
3
  value="Read PDF" />

21) 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 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. . . . .

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

23) 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:
1
2
javax.faces.CONFIG_FILES
3
/WEB-INF/faces-config-navigation.xml,
4
/WEB-INF/faces-beans.xml

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

24) How to mask actual URL to the JSF page?

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.
1
import java.io.IOException;
2
import java.util.Locale;
3

4
import javax.faces.FacesException;
5
import javax.faces.application.ViewHandler;
6
import javax.faces.component.UIViewRoot;
7
import javax.faces.context.FacesContext;
8

9
import org.apache.commons.logging.Log;
10
import org.apache.commons.logging.LogFactory;
11

12
/**
13
* A facade view handler which maps URIs into actual physical views that the
14
* underlying implementation can deal with regularly.
15
* Therefore, all internal references to view ids, for example in faces-config,
16
* will use the path to the physical files. Everything publicized, however, will
17
* see a "converted" / facade url.
18
*/
19
public abstract class SimpleConverterViewHandler
20
           extends ViewHandler {
21
private static final Log LOG =
22
         LogFactory.getLog(SimpleConverterViewHandler.class);
23

24
private final ViewHandler base;
25

26
public SimpleConverterViewHandler(ViewHandler base) {
27
this.base = base;
28
}
29

30
/**
31
* Distinguishes a URI from a physical file view.
32
* Tests if a view id is in the expected format -- the format corresponding
33
* to the physical file views, as opposed to the URIs.
34
* This test is necessary because JSF takes the view ID from the
35
* faces-config navigation, and calls renderView() on it, etc.
36
*/
37
public abstract boolean isViewFormat(FacesContext context, String viewId);
38

39
/**
40
* Convert a private file path (view id) into a public URI.
41
*/
42
public abstract String convertViewToURI(FacesContext context, String viewId);
43

44
/**
45
* Convert a public URI into a private file path (view id)
46
* note: uri always starts with "/";
47
*/
48
public abstract String convertURIToView(FacesContext context, String uri);
49

50
public String getActionURL(FacesContext context, String viewId) {
51
// NOTE: this is used for FORM actions.
52

53
String newViewId = convertViewToURI(context, viewId);
54
LOG.debug("getViewIdPath: " + viewId + "->" + newViewId);
55
return base.getActionURL(context, newViewId);
56
}
57

58
private String doConvertURIToView(FacesContext context, String requestURI) {
59
if (isViewFormat(context, requestURI)) {
60
return requestURI;
61
else {
62
return convertURIToView(context, requestURI);
63
}
64
}
65

66
public void renderView(FacesContext context, UIViewRoot viewToRender)
67
throws IOException, FacesException {
68
if (null == context || null == viewToRender)
69
throw new NullPointerException("null context or view");
70

71
String requestURI = viewToRender.getViewId();
72
String newViewId = doConvertURIToView(context, requestURI);
73
LOG.debug("renderView: " + requestURI + "->" + newViewId);
74
viewToRender.setViewId(newViewId);
75

76
base.renderView(context, viewToRender);
77
}
78

79
public UIViewRoot restoreView(FacesContext context, String viewId) {
80
String newViewId = doConvertURIToView(context, viewId);
81
LOG.debug("restoreView: " + viewId + "->" + newViewId);
82
return base.restoreView(context, newViewId);
83
}
84

85
public Locale calculateLocale(FacesContext arg0) {
86
return base.calculateLocale(arg0);
87
}
88

89
public String calculateRenderKitId(FacesContext arg0) {
90
return base.calculateRenderKitId(arg0);
91
}
92

93
public UIViewRoot createView(FacesContext arg0, String arg1) {
94
return base.createView(arg0, arg1);
95
}
96

97
public String getResourceURL(FacesContext arg0, String arg1) {
98
return base.getResourceURL(arg0, arg1);
99
}
100

101
public void writeState(FacesContext arg0) throws IOException {
102
base.writeState(arg0);
103
}
104

105
}

25) How to print out html markup with h:outputText?

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, This is a text

”/> will be printed out like: This is a text
In case of This is a text”/> you will get: This is a text

26) h:inputSecret field becomes empty when page is reloaded. How to fix this?

Set redisplay=true, it is false by default.
The following two tabs change content below.

No comments: