Sunteți pe pagina 1din 7

Introduction

The increased popularity of Web 2.0 is due largely to the flexibility of the current generation of web
browsers. These browsers use Ajax to communicate with the server to interchange XML data and
then employ DHTML to navigate the XML and present it to the user. The browser capabilities enable
them to be used as thick clients in a web based application.
These base technologies gave birth to a number of new technologies and initiatives to meet the
growing popularity of Web 2.0. New helper libraries like Dojo and Sarissa have been created to
make using XML less painful, and there has been increased support for Scalable Vector Graphics
(SVG). Embeddable widgets like Google and Yahoo Maps, data syndicatoin and integration
methodologies such as RSS and Atom feeds, and a new paradigm of developments using data
mashups have all been developed to meet the growing demands of the Web 2.0 culture.
As Figure 1 illustrates, the common glue in all the technologies is XML. The XML in the feeds makes
it possible to publish and ingest complex data structures over the web. DOM application
programming interfaces (APIs) in DHTML and XPath support in Sarissa allow efficient navigation of
the XML for reading and writing in the client.

Figure 1. Web oriented architecture

Note : In the Web 2.0 world where data sources are viewed as feeds and services, database drivers
are extended to support REST, FEED and SOAP calls. Once security implications have been resolved,
you will be able to access database routines directly using SOAP or REST calls not only from an
application server, but also from a web client, without having to create unnecessary mappings. In
the next article, the author creates a sample SOAP driver for DB2®.

<script type="text/javascript" src="sarissa/sarissa.js"></script>


<script language="javascript" type="text/javascript" src="xmlparse.js"></script>

Listing 1. Client requests customer information

<script>
function getCustomerInfo(cid)
{
var xmlhttpObj= new XMLHttpRequest();
var addr=hosturl+"?cmd= getuserprofile&msg="+cid;
var xmlhttpObj= new XMLHttpRequest();
xmlhttpObj.open('GET', addr, true);
xmlhttpObj.onreadystatechange = function() { customerInfoCallback(xmlhttpObj); };
xmlhttpObj.send("");
}
Listing 2. Application server retreives customer information
public void service( HttpServletRequest _req, HttpServletResponse _res)
throws ServletException, IOException
{

String cmd, msgtext, returnvalue;

if(_req.getMethod().equalsIgnoreCase("POST"))
{
String message = getPostBody(_req.getReader());
XMLParse msgxml=new XMLParse(message);
cmd= msgxml.getValue("//request/@cmd");
msgtext= msgxml.toString("/request/*");
}
else
{
cmd= _req.getParameter("cmd");
msgtext= _req.getParameter("msg");
}

Listing 3. Application server's response


if(cmd.equalsIgnoreCase("getuserprofile"))
{
//returnvalue= select CUSTXML from customer_table where customerid =msgtext
}
_res.setContentType("text/xml");
_res.getWriter().write(returnvalue);
_res.setHeader("Cache-Control", "no-cache");

Listing 4. Request for userinfo


var userinfo=null;
function customerInfoCallback (xmlhttp)
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{

Since the returned value from the server is XML, you pass it directly to the constructor of your DOM
wrapper.
userinfo= new xmlparse(xmlhttp.responseXML, false);

Next, you extract the first and last names from the XML using XPath.
var firstname = userinfo.getValue("/Customer/@firstname",null);
var lastname = userinfo.getValue("/Customer/@lastname",null);

Listing 5 shows how to use DHTML to create a graphical user interface (GUI) for the user name
modification and insert it into to the div tag, profilediv, that you declared in your HTML page.
Listing 5. DHTML that creates a GUI
var htmlstr="<table class='inputtable'><tr>";
htmlstr+='<td>firstname:</td><td><input id="fname" value="'+firstname+'"/></td>';
htmlstr+='<td>lastname:</td><td><input id="lname" value="'+lastname+'"/></td>';
htmlstr+='<tr><td/><td><input type="button" value="save"
onClick="javascript:updateCustomer()"/></td>';
htmlstr+='</tr></table>';
document.getElementById("profilediv").innerHTML=htmlstr;
}
}

Once you have done the modifications, click on the Save button to invoke the updateCustomer 
function. The DOM userinfo containing the customer information is updated with the user
modifications. Here again, you use XPath to navigate to the data nodes that need to be modified.

Listing 6. use XPath to update customer information


function updateCustomer()
{
var fname=document.getElementById("fname").value;
var lname=document.getElementById("lname").value;
userinfo.setValue("/Customer/@firstname",null,fname);
userinfo.setValue("/Customer/@lastname",null,lname);

A new request is created and the updated DOM is serialized and appended to it. Listing 7 shows the
request string then being sent (POST) to the server.
Note that since the message format is XML, the content type in the HTTP header of the request is
set to XML.

Listing 7. Request string sent to the server


var msg='<request cmd=" updateuserprofile">'+userinfo.toString("/")+'</request>';
var xmlhttpObj= new XMLHttpRequest();
xmlhttpObj.open('POST', hostname, true);
xmlhttpObj.onreadystatechange = function() { profileUpdated(xmlhttpObj); };
xmlhttpObj.setRequestHeader('content-type', 'text/xml');
xmlhttpObj.send(msg);
}

Application server Java code


The incoming customer XML data from the request is parsed using the DOM wrapper.
Since customerid is an attribute in the original customer profile that was sent to the client, there is
no need to send an extra parameter for the customer ID in the request.
Listing 8 shows how to extract the customerid from the XML and use it to create an update SQL
command for the database. The customer profile data from the HTTP request is passed as a
parameter to the update statement; no modifications are needed.

Listing 8. Create an update SQL command


else if(cmd.equalsIgnoreCase("updateuserprofile"))
{
XMLParse custxml=new XMLParse(msgtext);
String cid= custxml.getValue("/Customer/@customerid");
//update customer_table set custxml=? where customerid=cid
//stmt.setString(1,msgtext);
}

Notice the similarity in application code that is used to navigate the XML in both the client and the
server. Also, note that the applicatoin server in both the HTTP requests acted simply as a go-
between for the client and the database -- no data was manipulated in the interchange.
Calculate the insurance rates for items purchased
The user selects an insurance company from a drop down list that contains the names of all
insurance carriers. The insurance company has a web service that can be queried to get the current
insurance rates. The rate information is provided as an XML document and is used by the application
to calculate the insurance on each item.
Client JavaScript code
The URL for the associated web service provided by that insurance company is also selected from
the list. Since Ajax prevents URL redirection, you need to invoke the web service from the
application server. You pass the URL in the request to the application server for calculating the
insurance cost of each item purchased. Listing 9 shows tihs process:

Listing 9. Client selects URL


function itemsPurchased(url,cid)
{
var msg='<request cmd="getPurchaseInfoWithInsurance"><data customerid="cid">
<![CDATA['+ url+']]></data></request>';

var xmlhttpObj= new XMLHttpRequest();


xmlhttpObj.open('POST', hostname, true);
xmlhttpObj.onreadystatechange = function() { temsPurchasedCallback (xmlhttpObj); };
xmlhttpObj.setRequestHeader('content-type', 'text/xml');
xmlhttpObj.send(msg);
}
}

Note : Since the URL might contain special characters, we have embedded it inside a CDATA section
to prevent the request XML from becoming malformed.
Application server Java code
The request message is parsed using the DOM wrapper and the insurance URL is extracted from it.
Listing 10 shows how the application uses this URL to make a call to the web service of the
insurance provider to retrieve the XML document containing the insurance rates.

Listing 10. Application server retrieves insurance rates


else if(cmd.equalsIgnoreCase("getPurchaseInfoWithInsurance"))
{
XMLParse dataxml=new XMLParse(msgtext);
String url= dataxml.toString("/data/text()");
String insurancestr=callWebServiceUsingHTTPClient(url);

Note : The insurance rate XML is defined in Part 2, in the section entitled "A more elaborate
example." .
The customer ID is also extracted from the message and is used to query the database for
information on the items purchased by the customer.
String cid= dataxml.getValue("/data/@customerid");

The rest of the business logic for creating the purchased item list is implemented in either of two
ways:

1. Make a call to the database stored procedure created in Part 2>Listing 6.

// returnvalue = call customerItemsWithInsurance (cid, insurancestr);

2. Code the logic in the application server using the code from the first article. Using the
customerXML from Part 1: Listing 6 , loop through each item, calculate the insurance cost,
and add it to the item information.
Replace lines 9-11 in the original code with the following:

Listing 11. Replacement for lines 9-11

XMLParse insurancexml=new XMLParse(insurancestr);


customerXML.find("/Customer/Items/item",true);
String currency= insurancexml.getValue("//rate/@currency");

for(int i=0; customerXML.currentFind.getLength()>i;i++)


{
price = customerXML.getValue("@price",i));
if(price>500) rate= insurancexml.getValue("//rate[@price=""]/@rate"));
else If(price>100) rate= insurancexml.getValue("//rate[@price="500"]/@rate"));
else rate= insurancexml.getValue("//rate[@price="100"]/@rate"));
String iteminsurance="<insurance currency="+currency+ ">"+price*rate+"</insurance>"
customerXML. appendElement(customerXML.createNode (iteminsurance),
customerXML.getNode (null,i), false )
}
// returnvalue = customerXML.toString();

If you compare the above code to the query in the customerItemsWithInsurance stored procedure of
Article 2, you will note that there is a lot of similarity between the two, especially in the XPaths that
were used. This fact once again reinforces the advantage of using the XML model and the ease of
pushing business logic into the database.
Also note the power of XPath expressions to search and navigate inside the hierarchical XML Data
Model . Replicating this kind of search in an Object Data Model using java code would require a
great deal of effort. Using XPath simplifies the process and allowes it to be done with a single string
expression.
Client JavaScript code
The server response invokes the itemsPurchasedCallback function in which the returned XML data is
parsed using the DOM wrapper. Listing 12 shows how to do this:

Listing 12. XML is parsed using the DOM wrapper


function itemsPurchasedCallback (xmlhttp)
{

if (xmlhttp.readyState == 4 && xmlhttp.status == 200)


{
var itemInfo= new xmlparse(xmlhttp.responseXML, false);

First extract the user name from the returned XML:

Listing 13. Extract user name


var firstname = userinfo.getValue("/Customer/@firstname",null);
var lastname = userinfo.getValue("/Customer/@lastname",null);

var htmlstr="<table class='inputtable'>"


htmlstr+='<tr><td>firstname:<td colspan=5>'+firstname
htmlstr+='<tr><td>lastname:<td colspan=5>'+lastname
Then iterate through all the items in the document and extract the relevant information to create
the HTML string that is used to publish this information to the user.

Listing 14. Extract HTML that allows publishing


itemInfo.find("//item",null,true);
htmlstr+='<tr><td>itemID<td>description<td>date<td>price<td>insurance';
for(var j=0;itemInfo.currentFind.length>j ;j++)
{
var id= itemInfo.getValue("@ID",j);
var description= itemInfo.getValue("@description",j);
var purchaseDate= itemInfo.getValue("@purchaseDate",j);
var price= itemInfo.getValue("@price",j);
var insurance= itemInfo.getValue("insurance/text()",j);
var currency= itemInfo.getValue("insurance/@currency",j);
htmlstr+='<tr><td>'+id+'<td>'+description+'<td>' +purchaseDate+
'<td>' +currency+price++'<td>' +insurance;
}
document.getElementById("profilediv").innerHTML=htmlstr;
}

Note the similarity between the JavaScript code in the client that used XPath to search and iterate
over the item elements to that of the Java code in the application server defined before.

S-ar putea să vă placă și