Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

FacesClient Components, Part 3: Exchange data between FacesClient Components Web applications and backend servers

Detailing approaches for updating the client-side data model

Rod Henderson (rodhende@us.ibm.com), Advisory Software Engineer, IBM 
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 (ycli@us.ibm.com), Senior Software Engineer, IBM Software Group
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, Advisory Software Engineer, IBM 
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.

Summary:  In this third article in a series on FacesClient Components, we concentrate on the methods used to update the client-side data model. Using the prototype from the first and second articles of the series plus code samples, the authors describe how to update the client-side data model without causing a refresh of the entire portal page. The best practices described in this article serve as building blocks for creating highly functional FacesClient Component-enabled portlet applications.

View more content in this series

Date:  01 Mar 2005
Level:  Introductory

Activity:  2077 views
Comments:  

Introduction

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

  1. Dynamically create a hidden IFRAME (zero-sized IFRAME).
  2. Send the request to the server through the hidden IFRAME.
  3. The Server handles the request, creates the response data, and sends it back to the browser.
  4. The hidden IFRAME receives the response and passes the data to original parent window.
  5. The original parent window then merges the new data into the local FacesClient Components data model.
  6. 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.


Create a hidden IFRAME

You can apply the hidden IFRAME in two ways:

  1. Use the IFRAME to send a POST request to the server (see Listings 1 and 2).
  2. Send a GET request 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;
}


Construct the server response

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>



Handle the server response

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
The Java Beans view

In conclusion

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.


Resources

About the authors

Rod Henderson

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

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

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.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, WebSphere
ArticleID=48976
ArticleTitle=FacesClient Components, Part 3: Exchange data between FacesClient Components Web applications and backend servers
publish-date=03012005
author1-email=rodhende@us.ibm.com
author1-email-cc=htc@us.ibm.com
author2-email=ycli@us.ibm.com
author2-email-cc=htc@us.ibm.com
author3-email=tmcelroy@us.ibm.com
author3-email-cc=htc@us.ibm.com

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Try IBM PureSystems. No charge.

Special offers