With FacesClient Components, you can create rich and interactive Web-based applications that exhibit improved performance when compared with traditional, non-FacesClient Components-enabled Web applications. FacesClient Components-enabled Web applications realize better performance because fewer round trips to the server and less backend processing are needed to support the application. Additionally, you can design FacesClient Components applications to consume less network bandwidth when a required round trip to the server. A generated browser page for a FacesClient Components application consists of four parts: a SDO4JS set, the page runtime, a control library, and the HTML used to layout the page (see Figure 1). In general, you can design rich and interactive FacesClient Components applications so only the SDO4JS set (client-side data model) updates when the instance data changes as a result of a user's interaction with the application or completion of a backend transaction by another party (for example, stock price adjustments due to stock market activity).
Figure 1. Sample browser page

Create a UI that maximizes reuse of Web page markups
A good application development practice is to design your application user interface to maximize reuse of the Web page markups (such as a SDO4JS set, the page runtime, a control library, and the HTML used to layout the page) as much as possible. In this design approach, a browser-side component converses with the backend server when a transaction is submitted or more application data are needed for display. In this article (the third in a series), we introduce a way to perform data exchange between a FacesClient Components-enabled browser page and a backend server without page refresh.
To achieve the above goal of performing data exchanges without refreshing the Web page, you can use several protocols. Two example protocols are:
-
Web Service: FacesClient Components contain a Web Service control. With this control, invoke a Web Service directly from the browser. FacesClient Components JavaScript data object attributes are used for both input parameters and output results. -
HTTP Request/Response: Use HTTP to submit a request and receive a response.
In this document, we focus on how to use HTTP to exchange data between the browser and the server without a page refresh.
Use a hidden IFRAME for data exchange
A data exchange completed by submitting a simple HTTP request from the working
browser window reloads the entire Web page in the browser window from the Web server. A common trick is to use a hidden IFRAME to
avoid the reloading pitfall. The IFRAME was added to version 4 of the HTML
specification and most modern browsers provide support for it. Using hidden
IFRAMES and FacesClient Components, a developer can create complex interfaces, which interact
seamlessly with the server. The main steps needed to use hidden IFRAMES to
exchange data between an FacesClient Component-enabled client-side application running in the
browser and a server-side application are
- Dynamically create a hidden
IFRAME(zero-sizedIFRAME). - Send the request to the server through the hidden
IFRAME. - The Server handles the request, creates the response data, and sends it back to the browser.
- The hidden
IFRAMEreceives the response and passes the data to original parent window. - The original parent window then merges the new data into the local FacesClient Components data model.
- The new data then shows in all the FacesClient Components controls that bind to it.
In the follow sections, we describe each step in detail and provide sample code.
You can apply the hidden IFRAME in two ways:
- Use the
IFRAMEto send aPOSTrequest to the server (see Listings 1 and 2). - Send a
GETrequest to the server (see Listing 3).
With a POST request you write the form as
usual. Next, you create the hidden IFRAME as shown in Listing 1, set the form target to RSIFrame as shown in Listing 2, and then submit the form (see
Listing 2).
Listing 1. JavaScript function: Create a hidden
IFRAME
var IFrameObj; // our IFrame object
// create a hidden iframe to post a request to portal server
// and get response without refreshing the original portal page.
function createIFrame() {
if (!document.createElement) {return true};
// var IFrameDoc;
var ie = false;
if (navigator.appName == "Microsoft Internet Explorer")
ie = true;
if (!IFrameObj && document.createElement) {
// create the IFrame and assign a reference to the
// object to our global variable IFrameObj.
// this will only happen the first time
// callToServer() is called
var sIframe = (ie)?'<iframe name="RSIFrame"></iframe>':'iframe'
// var tempIFrame=document.createElement('iframe');
var tempIFrame=document.createElement(sIframe);
tempIFrame.setAttribute('id','RSIFrame');
if (!ie)
tempIFrame.setAttribute('name','RSIFrame');
tempIFrame.style.border='0px';
tempIFrame.style.width='0px';
tempIFrame.style.height='0px';
IFrameObj = document.body.appendChild(tempIFrame);
if (document.frames) {
// this is for IE5 Mac, because it will only
// allow access to the document object
// of the IFrame if we access it through
// the document.frames array
IFrameObj = document.frames['RSIFrame'];
}
}
if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
// we have to give NS6 a fraction of a second
// to recognize the new IFrame
setTimeout('invoke()', 10);
return false;
}
return false;
}
|
Listing 2. JavaScript code: Submit the form through the hidden
IFRAME
// Ask the user to confirmation the fund transfer transaction
function maketransfer(myform, fromBankAcct, toBankAcct, amount) {
var message ="\nYou are about to transfer $" + amount + "\n" +
"from account " + fromBankAcct.GetBankAcctNum() + " to account "
+ toBankAcct.GetBankAcctNum() + "\n" + "\n"
+ "After transfer, you will have following new balance:\n" + "\n"
+ " " + fromBankAcct.GetBankAcctNum() + ": $"
+ (fromBankAcct.GetBalance() - amount) + "\n" + " "
+ toBankAcct.GetBankAcctNum() + ": $" + (toBankAcct.GetBalance() + amount)
+ "\n" + "\n" + "Are you ready to make the transfer?"
if (confirm(message)) {
_fromAccount = fromBankAcct;
_toAccount = toBankAcct;
createIFrame();
myform.target = "RSIFrame";
myform.submit();
}
}
|
An added benefit of this approach is the minimal amount of JavaScript code
needed to submit the request. Additionally, no limit is imposed on the
length of parameter names and their value. However, since the post action is
initiated from the main browser window, the request URL is saved in the
browser's history, and it can impact the browser RELOAD and BACK action. One
solution for this problem is to add some server code to distinguish whether a
new request is new or it is just a RELOAD action. If it is a RELOAD action,
then the application must forward the request to the right page handler. To accomplish this action, send JavaScript code to the browser to redirect it to the correct URL.
A developer might use the GET request as an alternative
means of applying the hidden IFRAME. In this approach, the application
developer must append all parameters and their values to the
request URL. The JavaScript function in Listing 3 works and is invoked
without any change. An added benefit of this approach is that the request is
not recorded in the browser's history; therefore, it does not affect
browser RELOAD and BACK operations. A drawback of this approach is that all the
parameters and their values must be appended to the request URL. In some
browser implementations, the length of the request URL has a maximum limit.
Listing 3. JavaScript Function: Hidden IFRAME using the GET method
var IFrameObj; // our IFrame object
function callToServer(URL) {
if (!document.createElement) {return true};
var IFrameDoc;
if (!IFrameObj && document.createElement) {
// create the IFrame and assign a reference to the
// object to our global variable IFrameObj.
// this will only happen the first time
// callToServer() is called
var tempIFrame=document.createElement('iframe');
tempIFrame.setAttribute('id','RSIFrame');
tempIFrame.style.border='0px';
tempIFrame.style.width='0px';
tempIFrame.style.height='0px';
IFrameObj = document.body.appendChild(tempIFrame);
if (document.frames) {
// this is for IE5 Mac, because it will only
// allow access to the document object
// of the IFrame if we access it through
// the document.frames array
IFrameObj = document.frames['RSIFrame'];
}
}
if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
// we have to give NS6 a fraction of a second
// to recognize the new IFrame
//// setTimeout('callToServer("'+theFormName+'")',10);
setTimeout('callToServer("'+from+', '+to+', '+amount+'")',10);
return false;
}
if (IFrameObj.contentDocument) {
// For NS6
IFrameDoc = IFrameObj.contentDocument;
} else if (IFrameObj.contentWindow) {
// For IE5.5 and IE6
IFrameDoc = IFrameObj.contentWindow.document;
} else if (IFrameObj.document) {
// For IE5
IFrameDoc = IFrameObj.document;
} else {
return true;
}
IFrameDoc.location.replace(URL);
return false;
}
|
After the server processes the GET or PUT request, it sends a response that contains the
updated data, which will be applied to the browser's local data model. This is
similar to the process of creating a data model and instance data as described in our
first article. Listing 4 shows the sample code from Customer Loyality prototype described in our
first article. The sample code is server-side code used to
create a new data object. The newly created CustomerAccountData object contains
the customer's new/updated banking account and transaction data, which are subsequently added to the servlet request.
Listing 5 shows the JavaScript code used to
pass the data change obtained from the server to the original browser window
where the parent.handleResponse() method is invoked. A
JavaScript function named handleResponse was implemented inside the original Web
page to update the local data model.
Listing 5. JSP Code: Server Respond Code
<jsp:useBean id="deltaCustomerAccount"
class="com.ibm.shcl.ciis.data.CustomerAccountData" scope="request" />
<jsp:useBean id="ODCPCTX"
class="com.ibm.odcb.jrender.mediators.PageContext" scope="request" />
<portletAPI:init/>
<%
boolean jcomplete =
((Boolean) portletRequest.getAttribute("Complete")).booleanValue();
if (jcomplete) {
PortletURLRewriter portletURLRewriter = new
PortletURLRewriter(portletResponse);
InitializationEmitter Init =
new InitializationEmitter(true, -1, "en", "", portletURLRewriter, 2);
Init.Export(out, ODCPCTX);
WDO4JSEmitter E = new WDO4JSEmitter();
E.Init(deltaCustomerAccount,
deltaCustomerAccount.getClass().getName(), "Banking",
true, true, "Customer");
E.ExportModel(out, ODCPCTX);
E.ExportData(out, ODCPCTX);
}
%>
<script>
var complete = <%= jcomplete %>;
if (complete) {
var user = WDO4JSModelRoot_Customer.Root.GetBanking_Cus()[0];
var BankAccounts = user.GetBankingAccounts();
if (parent != self) {
parent.handleResponse(complete, BankAccounts);
}
} else {
if (parent != self) {
parent.handleResponse(complete, null);
}
}
</script>
|
The FacesClient Component framework includes JavaScript API's designed to handle server responses and to manage the client-side data model. Listing 6 shows the sample code from the Customer Loyality prototype. This code handles the server's response to a funds transfer. Figure 2 shows a funds transfer executed using the eTransfer Funds portlet. The server generates a response for a fund transfer request that includes: new balances for two accounts and two new transactions. Therefore, the local data model updates to reflect the new data changes. To revise each account balance, you must find those accounts involved in the funds transfer and set the balance attribute of each account using the new values. The new transactions are added to the account transaction list for the particular accounts. Once the data changes are made, FacesClient Component controls that bind to those modified data objects refresh automatically . The last step is to notify the user that the server either successfully or unsuccessfully processed the request using a dialog or other means.
Listing 6. JavaScript Function: Handle Server Response
// handleResponse implements the callback function from the response
// in the hidden iframe generated from the portal server.
function handleResponse(complete, BankingAccounts) {
var message = "Fund transfer aborted, please try later!";
if (complete) {
var bankAccount;
for (var i = 0; i < BankingAccounts.length; i++) {
bankAccount = BankingAccounts[i];
if (bankAccount.GetBankAcctNum() == _fromAccount.GetBankAcctNum())
break;
}
// update from account
_fromAccount.eAdd("BankingTrans", bankAccount.GetBankingTrans()[0]);
_fromAccount.SetBalance(bankAccount.GetBalance());
for (var i = 0; i < BankingAccounts.length; i++) {
bankAccount = BankingAccounts[i];
if (bankAccount.GetBankAcctNum() == _toAccount.GetBankAcctNum())
break;
}
// update to account
_toAccount.eAdd("BankingTrans", bankAccount.GetBankingTrans()[0]);
_toAccount.SetBalance(bankAccount.GetBalance());
message = "Fund transfer was completed successful! Click ok to continue.";
}
// refresh the fund transfer selection list
ShowSelectList("FROMACCTKEY");
ShowSelectList("TOACCTKEY");
document.transferForm.amount.value = "";
// alert the user about the end of the transaction
alert(message);
}
|
Figure 2. Funds transfer

You can design FacesClient Components applications to update only the client-side data model when the instance data changes as a result of a user's interaction with the application or completion of a backend transaction by another party (for example, stock price adjustments due to stock market activity). In this article, we discussed how to update the client-side data model without refreshing the portal page. We presented sample code from the Customer Loyalty prototype implementation and addressed how to use FacesClient Components to make portal pages more responsive and interactive.
-
Visit the WebSphere zone at developerWorks for software downloads, white papers, tutorials, and developer training for the WebSphere platform.
-
At the Eclipse
Project, learn about the Eclipse Modeling Framework (EMF), a code-generating
tool for building tools and other applications based on a structured data model
as described in XMI.
- In the Portlet
Development Guide, 2nd Ed." learn to develop a portlet using the Portlet API 1.2. This guide also describes Portlet API concepts and its elements (developerWorks, March 2003).
- Read the "FacesClient
Components Developer's Guide" (PDF) as it describes the different FacesClient Components, and shows how to use them with WebSphere Studio to build Web and portlet applications (developerWorks, November 2004).
- In "Consumer
self-service: Develop and deploy rich clients on the portal" discover how to fulfill the title's promise using FacesClient Components (developerWorks, November 2004).
- Read the other articles in this developerWorks series:
- FacesClient Components, Part 1: Portlet programming with FacesClient Components" (developerWorks, November 2004).
- " FacesClient Components, Part 2: Use FacesClient Components in a portal environment" (developerWorks, November 2004).
- Get the details on FacesClient Components' cutting-edge, pattern-based structure in "iSeries EXTRA: A Web Tooling Odyessy" (IBM eServer Magazine, June 2004).
- Browse for books on these and other technical topics.
- Find step-by-step instructions for creating a portlet application that includes portlet messaging in
"Implementing portlet messaging using WebSphere Studio Application Developer V5 and the Portal Toolkit V5" (developerWorks, February 2004).
- Learn to coordinate the behavior of multiple portlets in a seamless fashion in "Using
Cooperative Portlets in WebSphere Portal V5" (developerWorks, October 2003).
- Visit the developerWorks Web Architecture zone for articles covering various Web-based solutions.

Rod Henderson is an advisory software engineer in the IBM Software Group, System House, Advanced Technology Department located in Research Triangle Park, North Carolina. He received his PhD in electrical engineering from North Carolina A&T State University in 2002. Currently, he is actively involved in advanced technology projects in the areas of rich client technology, solution integration, and scenario-based software development. Contact Rod at rodhende@us.ibm.com.

Yongcheng Li is a Senior Software Engineer in the IBM Software Group, System House, Advanced Technology Department located in Research Triangle Park, North Carolina. He received his Ph.D. in Computer Science from Tsinghua University in 1993. He is actively involved in advanced technology projects in the areas of rich client technology, data caching and replication, solution integration, and scenario-based software development. Send e-mail to Yongcheng at ycli@us.ibm.com.

Thomas McElroy is an advisory software engineer in the IBM Software Group's System House organization, located in Research Triangle Park, North Carolina. He has been working on Web-application technology projects for the last three years, including projects with the on-demand clients, edge-side includes, integrated solutions console, and a novel approach to a JDBC (Java Database Connectivity) caching proxy. You can reach Thomas at tmcelroy@us.ibm.com.




