AsynchronousJavaScriptandXML(AJAX)withJava2Enterpri…

来源:互联网 发布:linux安装多版本jdk 编辑:程序博客网 时间:2024/04/30 05:54
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

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

  ThemaindrawbackwiththisapproachisthattheHTMLthatissetasthebodyoftheintotheelementbodywillbehardcodedasstringintheJavaScriptincludingothermarkupliketheelement.IntermixingpresentationwithJavaScriptcodeasstringswillmakeapagedifficultreadandedit.

  AnothermeansofmodifyingtheHTMLDOMistodynamicallycreatenewelementsandappendthemaschildrentoatargetelementascanbeseeninthefollowingexample.

 

 

 

 

  ThecodesampleaboveshowshowJavaScriptDOMAPIsmaybeusedtocreateanelementoraltertheelementprogramatically.TheJavaScriptDOMAPIssupportinvariousbrowserscandiffersocareneedstobetakenwhendevelopingapplications.

  FinalThoughts

  WehaveseenthattherearemanypossibleproblemsthatAJAXinteractionscansolve.J2EEtechnologyprovidesagoodbasetodevelopanddeployAJAXbasedapplicationswithAPIsfortyinginHTTPprocessing,databases,webservices,XMLprocessingandbusinessobjects.Withabetterunderstandingofthisinteractionmodel,today'sapplicationscanbecomemoreinteractiveprovidingabetterexperiencetotheenduser.

  Thisdocumentdescribedcommonusecases,technologiesinvolved,andreviewedtheanatonmyofanAJAXinteraction.Pleaserefertothevarioussolutionentriesformorespecficexamples.

  References

  TheAppleDeveloperconnectionhassomegooddocumentationontheXMLHttpRequestobject.

  TheJavaScriptDOMbindingsdefinedbytheW3C.

  AgreatreferenceforJavaScriptandCSSsupportinbrowsersmaybefoundathttp://www.quirksmode.org/.

  DefintionofAJAXbyJesseJamesGarrett.

  --------------------------------------------------------------------------------

  ?SunMicrosystems2005.AllofthematerialinTheJavaBluePrintsSolutionsCatalogiscopyright-protectedandmaynotbepublishedinotherworkswithoutexpresswrittenpermissionfromSunMicro

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击