ajax|erp|javascript|xml
AsynchronousJavaScriptandXML(AJAX)withJava2EnterpriseEdition
AnyonewhohasusedFlickr,GMail,GoogleSuggest,orGoogleMapswillrealizethatanewbreedofdynamicwebapplicationsareemerging.Theseapplicationslookandactverysimilartotraditionaldesktopapplicationswithoutrelyingonpluginsorbrowserspecificfeatures.WebapplicationshavetraditionallybeenasetofHTMLpagesthatmustbereloadedtochangeanyportionofthecontent.Overthepastfewyears,technologiessuchasJavaScriptandCascadingStyleSheet(CSS)havematuredtothepointwheretheycanbeusedeffectivelytocreateverydynamicwebapplicationsthatwillworkonallofthemajorbrowsers.Thisdocumentandthesolutionsassociatedwithitwilldetailseveraltechniquesthatyoucanusetodaytoenableyourwebapplicationstobemorerichandinteractivelikedesktopapplications.
IntroducingAsynchronousJavaScriptandXML(AJAX)
UsingJavaScriptanHTMLpagecanasynchronouslymakecallstotheserverfromwhichitwasloadedandfetchXMLdocuments.TheXMLdocumentsmaythenbeusedbyJavaScripttoupdateormodifytheDocumentObjectModel(DOM)oftheHTMLpage.ThetermAsynchronousJavaScriptandXML(AJAX)hasemergedrecentlytodescribethisinteractionmodel.
AJAXisnotnew.ThesetechniqueshavebeenavailabletodeveloperstargetingInternetExplorer(IE)ontheWindowsplatformformanyyears.Upuntilrecentlythetechnologywasreferredtoaswebremotingorremotescripting.Webdevelopershavealsousedacombinationofplugins,Javaapplets,andhiddenframestoemulatethisinteractionmodelforsometime.WhathaschangedrecentlyisthattheinclusionofsupportfortheXMLHttpRequestobjecthasbecameubiquitousinthemainstreambrowsersacrossallplatforms.TherealmagicistheresultoftheJavaScriptXMLHttpRequestobject.WhilethisobjectisnotspecifiedintheformalJavaScriptspecification,itissupportedbyallofthemainstreambrowserstoday.WhiletherearesubtledifferenceswiththeJavaScriptandCSSsupportamongcurrentgenerationbrowserssuchasFirefox,IEandSafari,theyaremanageable.Ifyouarerequiredtosupportolderbrowsers,AJAXmaynotbetheanswerforyou.
WhatmakesAJAXbasedclientsuniqueisthattheclientcontainspagespecificcontrollogicembeddedasJavaScript.ThepageinteractswiththeJavaScriptbasedoneventssuchasthedocumentbeingloaded,amouseclick,focuschanges,orevenatimer.AJAXinteractionsallowforaclearseparationofpresentationlogicfromthedata.AnHTMLpagecanpullinbitesizepiecesofdataasneededversusreloadingthewholepageeverytimeachangeneedstobedisplayed.AJAXwillrequireadifferentserver-sidearchitecturetosupportthisinteractionmodel.Traditionally,server-sidewebapplicationshavefocusedongeneratingHTMLdocumentsforeveryclienteventresultinginacalltotheserverandtheclientswouldrefreshandre-renderthecompleteHTMLpageforeachresponse.RichwebapplicationsfocusonaclientfetchinganHTMLdocumentwhichactsasatemplateorcontainerforinjectingcontentintobasedonclienteventsusingXMLdataretrievedfromaserver-sidecomponent.
SomeusecasesforAJAXinteractionsare:
RealtimeFormDataValidation:Formdatasuchasuserids,serialnumbers,postalcodes,orevenspecialcouponcodesthatrequireserver-sidevalidationcanbevalidatedinaformbeforetheusersubmitsaform.
Auto-Completion:Aspecificportionofformdatasuchasanemailaddress,name,orcitynamemaybeauto-completedastheusertypes.
MasterDetailsOperations:BasedonaclienteventanHTMLpagecanfetchmoredetailedinformationondatasuchasaproductlistingthatenablestheclienttoviewtheindividualproductinformationwithoutrefreshingthepage.
SophisticatedUserInterfaceControls:Controlssuchastreecontrols,menus,andprogressbarsmaybeprovidedthatdonotrequirepagerefreshes.
RefreshingDataonthePage:HTMLpagesmaypolldatafromaserverforuptodatedatasuchasscores,stockquotes,weather,orapplicationspecficdata.
Server-sideNotifications:AnHTMLpagemaysimulateaserver-sidepushbypollingtheserverforeventnotificationswhichmaynotifytheclientwithamessage,refreshpagedata,orredirecttheclienttoanotherpage.
Thislistisnotallinclusive,however,itdoesshowthatAJAXinteractionsallowwebapplicationstodomuchmorethantheyhavetraditionallydoneinthepast.Whilemanyofthesebenefitsarenoteworthytherearesomedrawbackstothisapproachaswell:
Complexity:Server-sidedeveloperswillneedtounderstandthatpresentationlogicwillberequiredintheHTMLclientpagesaswellasintheserver-sidelogictogeneratetheXMLcontentneededbytheclientHTMLpages.JavaScriptskillsarerequiredfortheHTMLpagedevelopers.OvertimeitwillbecomeeasiertocreateAJAXenabledapplicationsasnewframeworksarecreatedandexistingframeworksevolvetosupporttheinteractionmodel.
StandardizationoftheXMLHttpRequestObject:TheXMLHttpRequestisnotyetapartoftheJavaScriptspecificationwhichmeansthatthebehaviormayvarydependingontheclient.
JavaScriptImplementations:AJAXinteractionsdependheavilyonJavaScriptwhichhassubtledifferencesdependingontheclient(seeQuirksMode.orgformoredetailsonbrowserspecificdifferences.
Debugging:AJAXapplicationsarealsodifficulttodebugbecausetheprocessinglogicisbothembeddedintheclientandontheserver.
ViewableSource:TheclientsideJavaScriptmaybeviewedbytheclientbysimplyselecting"ViewSource"formanAJAXenabledHTMLpage.ApoorlydesignedAJAXbasedapplicationcouldopenitselfuptohackersorplagarism.
FrameworksandpatternsforAJAXtechnologyarelikelytoemergeasdevelopersgainmoreexperiencedwrittingapplicationsthatusetheAJAXinteractionmodel.Itisstillearlytofocusona"onesizefitsall"frameworkforAJAXinteractions.ThisdocumentandtheassociatedsolutionsfocusonhowAJAXinteractionscanbesupportedtodaybyexistingJava2EnterpriseEdition(J2EE)technologiessuchservlets,JavaServerPages,JavaServerFacesandtheJavaStandardTagLibraries(JSTL).
TheAnatomyofanAJAXinteraction
NowthatwehavediscussedwhatAJAXisandwhatsomehigherlevelissuesare,let'sputallthepiecestogetherandshowanAJAXenabledJ2EEapplication.
Let'sconsideranexample,awebapplicationcontainsastaticHTMLpageoranHTMLpagegeneratedinJSPtechnologycontainsanHTMLformthatrequiresserver-sidelogictovalidatetoformdatawithoutrefreshingthepage.Aserver-sidewebcomponent(servlet)namedValidateServletwillprovidethevalidationlogic.ThegraphicbelowdescribesthedetailsoftheAJAXinteractionthatwillprovidethevalidationlogic.
TheitemsbelowrepresentthesetupsofanAJAXinteractionastheyappearinthegraphicabove.
Aclienteventoccurs.
AnXMLHttpRequestobjectiscreatedandinitialized.
TheXMLHttpRequestobjectmakesacall.
TherequestisprocessedbytheValidationServlet.
TheValidationServletreturnsanXMLDocumentcontainingtheresult.
TheXMLHttpRequestobjectcallsthecallback()functionandprocessestheresult.
TheHTMLDOMisupdated.
NowletlookateachstepoftheAJAXinteractioninmoredetail.
1.Aclienteventoccurs.
JavaScriptfunctionsarecalledastheresultofanevent.Inthecasethefunctionvalidate()maybemappedtoaonkeyupeventonalinkorformcomponent.
size="20" id="userid" name="id" onkeyup="validate();"> Theformelementabovewillcallthevalidate()eachtimeakeyispressedintheformfield. 2.AXMLHttpRequestobjectiscreatedandinitialized. AnXMLHttpRequestobjectisinitializedandconfigured. varreq; functionvalidate(){ varidField=document.getElementById("idField"); varurl="validate?id="+escape(idField.value); if(window.XMLHttpRequest){ req=newXMLHttpRequest(); }elseif(window.ActiveXObject){ req=newActiveXObject("Microsoft.XMLHTTP"); } req.open("GET",url,true); req.onreadystatechange=callback; req.send(null); } Thevalidate()functioninitializesaXMLHttpRequestobjectopenmethodrequiresthreeargumentswhicharewithaurlStringofGETorPOSTrepresetingtheHTTPmethodtobeused,aStringforthetargetURL,andabooleanindicatingwhetherornotthecallwillbemadeasynchronously.Ifaninteractionissetasasynchronous(true)acallbackfuctionmustbespecfied.Thecallbackfunctionforthisinteractionissetwiththestatementreq.onreadystatechange=callback;.Seethesectiontitled"TheXMLHttpRequestobjectcallsthecallback()functionandprocessestheresult"formoredetails. 3.TheXMLHttpRequestobjectmakesacall. Whenthestatmentreq.send(null);isreachedthecallwillbemade.InthecaseofaHTTPgetthiscontentmaybenullorleftblank.WhenthethisfunctioniscalledontheXMLHttpRequestobjectthecalltotheURLthatwassetduringtheinitializationoftheobjectiscalled.Inthecaseofthisexamplethedatathatisposted(id)isincludedasaURLparameter. UseanHTTPGETwhentherequestisidempotentmeaningthattwoduplicaterequestswillreturnthesameresults.WhenusingHTTPGETmethodthelengthofURLincludingescapedURLparametersislimitedbysomebrowsersandbyserver-sidewebcontainers.TheHTTPPOSTmethodshouldbeusedwhensendingdatatotheserverthatwilleffecttheserver-sideapplicationstate.AHTTPPOSTrequiresaContent-TypeheadertobesetontheXMLHttpRequestobjectbyusingthefollowingstatement: req.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); req.send("id="+escape(idTextField.value)); WhensendingformvaluesfromJavaScriptyoushouldtakeintoconsiderationtheencodingofthefieldvalues.JavaScriptincludesanescape()functionwhichshouldbeusedtoensurelocalizedcontentisencodedproperlyandthatspecialcharachtersareescapedcorrectly. 4.TherequestisprocessedbytheValidationServlet. AservletmappedtotheURI"validate"checksiftheuseridisintheuserdatabseornot. AservletprocessesaXMLHttpRequestjustasitwouldanyotherHTTPrequest.Theexamplebelowshowaserverextractingtheidparameterfromtherequestandvalidatingwhetherornottheparameterhasbeentaken. publicclassValidationServletextendsHttpServlet{ privateServletContextcontext; privateHashMapusers=newHashMap(); publicvoidinit(ServletConfigconfig)throwsServletException{ this.context=config.getServletContext(); users.put("greg","accountdata"); users.put("duke","accountdata"); } publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsIOException,ServletException{ StringtargetId=request.getParameter("id"); if((targetId!=null)&&!users.containsKey(targetId.trim())){ response.setContentType("text/xml"); response.setHeader("Cache-Control","no-cache"); response.getWriter().write("valid"); }else{ response.setContentType("text/xml"); response.setHeader("Cache-Control","no-cache"); response.getWriter().write("invalid"); } } } InthisexampleasimpleHashMapisusedtocontaintheusers.Inthecaseofthisexampleletusassumetheuserid"duke"wassubmitted. 5.TheValidationServletreturnsanXMLDocument. Theuserid"duke"ispresentinthelistofuseridsintheusersHashMap.TheValidationServletwillwriteaXMLdocumenttotheresponsecontainingan"message"elementwiththevalueof"invalid".MorecomplexusecasesmayrequireDOM,XSLT,orotherAPIstogeneratetheresponse. response.setContentType("text/xml"); response.setHeader("Cache-Control","no-cache"); response.getWriter().write("invalid"); TwothingsthatadeveloperneedstobeawareofisthattheContent-Typeissetto"text/xml"andtheCache-Controlneedstobesetto"no-cache".TheXMLHttpRequestobjectwillonlyprocessrequeststhatareoftheContent-Typeof"text/xml"andtheCache-Controlbeingsetto"no-cache"willkeepbrowsersfromlocallycachingresponsesforcaseswhereduplicaterequestsforthesameURL(includingURLparameters)mayreturndifferentresponses. 6.TheXMLHttpRequestobjectcallsthecallback()functionandprocessestheresult. TheXMLHttpRequestobjectwasconfiguredtocallthecallback()functionwhentherearechangestothereadyStateoftheXMLHttpRequestobject.LetusassumethecalltotheValidationServletwasmadeandthereadyStateis"4"signifyingtheXMLHttpRequestcalliscomplete.TheHTTPstatuscodeof"200"signifiesasuccessfulHTTPinteraction. functioncallback(){ if(req.readyState==4){ if(req.status==200){ //updatetheHTMLDOMbasedonwhetherornotmessageisvalid } } } Browsersmaintainanobjectrepresentationofthedocumentsbeingdisplayed(referredtoasthedocumentobjectmodel(DOM)).JavaScriptinanHTMLpagehasaccesstotheDOMandAPIsareavailablethatallowJavaScripttomodifytheDOMafterthepagehasloaded. Followingasuccessfulrequest,JavaScriptcodemaymodifytheDOMoftheHTMLpage.TheobjectrepresentationoftheXMLdocumentthatwasretrievedfromtheValidationServletisavailabletoJavaScriptcodeusingthereq.responseXMLwherereqisanXMLHttpRequestobject.TheDOMAPIsprovideameansforJavaScripttonavigatethecontentfromthatdocumentandusethatcontenttomodifytheDOMoftheHTMLpage.Astringrepresentationofthedocumentthatwasretrievedbycallingreq.responseText.NowletuslookatthehowtousetheDOMAPIsinJavaScriptbylookingatthefollowingXMLdocumentreturnedfromtheValidateServlet. valid TheexampleaboveisasimpleXMLfragmentthatcontainsthesenderofthemessageelementwhichissimplythestring"valid"or"invalid".Amoreadvancedsamplemaycontainmorethanonemessageandvalidnamesthatmightbepresentedtotheuser. functionparseMessage(){ varmessage=req.responseXML.getElementsByTagName("message")[0]; setMessage(message.childNodes[0].nodeValue); } TheparseMessages()functionwillprocessXMLdocumentretrievedfromtheValidationServlet.ThisfunctionwillcallthesetMessage()withvalueofthemessageelementtoupdatetheHTMLDOM. 7.TheHTMLDOMisupdated. JavaScriptcangainareferencetoanyelementintheHTMLDOMusinganumberofAPIs.Therecommendedwaytogainareferencetoaelementistocalldocument.getElementById("userIdMessage")where"userIdMessage"istheidattributeofanelementappearingintheHTMLdocument.WithareferencetotheelementJavaScriptmaynowbeusedtomaybemodifyattributesoftheelement,modifythestylepropertiesofelement,oraddorremove,modifychildelements. OnecommonmeanstochangethebodycontentofanelementistosettheinnerHTMLpropertyontheelementascanbeseeninthefollowingexample.
TheportionsoftheHTMLpagethatwereaffectedarere-renderedimmediatelyfollowingthesettingoftheinnerHTML.IftheinnerHTMLpropertycontainselementssuchas