仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 2406|回复: 20
打印 上一主题 下一主题

[学习教程] JAVA网站制作之Remote scripting using a servlet

[复制链接]
若天明 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-18 11:48:46 | 显示全部楼层 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
j2EE和asp比较,其实也没什么比的,原因和我上面说那些比较差不了多少,也是稳定性,安全性,J2EE比asp高,速度上比不过asp,asp也是延续着它的拖拽控件的方法,提高速度。servlet
ErikHatcher(erik@hatcher.net)President,eHatcherSolutions,Inc.01Feb2001
TheusersofWebapplicationshavesufferedadramaticshiftinexperiencesfromtheworldofdesktopapplications.ManyWebapplicationsdonotatallmimictheusability,interactivity,anddynamicnaturethatisavailableintypicalstandaloneorclient-serverdesktopapplicationsbecauseoftheconstraintsthatHTMLandHTTPimpose.Here,ErikHatcherexplainshowremotescriptingcanbeusedtoenhancetheinteractivityanddynamicnatureofaWebapplicationexperience.
OneofthemajordrawbackstoWebapplicationsisthattheuserexperienceistypicallyinferiortothatofdesktopapplications.MostcurrentWebapplicationslackininteractivitybecauseoncethebrowserreceivesaresponsetoitsURLrequestitisonitsown,failingtocommunicatebacktotheserveruntilahyperlinkisclickedoraformissubmitted.TechniquessuchasusingJavaScriptandDHTMLcanbeusedtomakethebrowserfeelmorelikeadesktopapplication;fanciertechniqueslikeusingFlash,ActiveX,andJavaappletscanalsoaccomplishthisend.

Butevenwiththesenewertechniquesandtechnologies,theclientisstillmostlyonitsownafteritreceivesthecontentfromtheWebserver.ThetechniquedescribedinthisarticleoffersasolutionthatallowsthebrowserandWebservertocommunicatebehindthescenes.ThebrowsercaninvokeremoteJavaservletmethodsthatenabletheuserexperiencetoresemblethatofadesktopapplication,suchaspopulatingadrop-downboxdynamicallybasedontheselectionofarelateddrop-downbox(thatis,category/subcategory),orpollingtheserverformessagesandrefreshingthedisplaydynamicallywithcontinuouslyupdatedcontent.

ClientsideTherearetwopopularwaysofaccomplishingremotemethodinvocationfromaWebbrowser:Microsoftremotescripting(MSRS)andBrentAshleysJavaScriptremotescripting(JSRS).Thegoalofbothisthesame:toinvokeremotemethodsandreturntheresultstothebrowser.BothmethodswereoriginallydesignedtocommunicatewithremotemethodsdefinedinMicrosoftsActiveServerPages.ThisarticleprovidesawayforbothofthesemethodstocommunicatewithaJavaservletontheserverside.Letsgetintothearchitecturedetailsofeachofthesetechniques.

RedmondscriptingMicrosoftsremotescriptingispartoftheVisualInterDevdevelopmentenvironment.Itconsistsofthreepieces:aninvisibleJavaapplet,client-sideJavaScript,andserver-sideJavaScriptrunninginActiveServerPages.TheJavaapplethandlesthecommunicationswiththeserver.Theclient-sideJavaScriptcommunicateswiththeapplet.Theserver-sideJavaScriptdealswithtakingtherequestedparametersanddispatchingthemtothespecifiedserver-sidemethod.ThecommunicationsaresimplyHTTPGETrequestsandresponses,withthedetailsofthemethodcallsentasqueryparameterstotheserver-sidescript.ThereismuchmoretobesaidaboutMicrosoftsremotescriptingarchitecture,butthatisbeyondthescopeofthisarticle(seeResources).

Figure1showsthearchitectureofMicrosoftremotescriptingusingaservletontheserver-side.

StepsinvolvedininvokingaremotemethodusingMicrosoftremotescripting:
ThebrowserexecutesaJavaScriptcalltoRSExecute(thisresidesinanincludedJavaScriptframeworkprovidedbyMicrosoftVisualInterDev).TheremotescriptingappletusesHTTPGETtoaccessaspecialservletURLontheserver,completewithmethodnameandparameters.TheservletreturnsitsXML-likeresponseandtheappletreceivesit.TheresponseisinterpretedbytheremotescriptingJavaScriptandreturnedtothecallingcode.Acallobjectisreturned,andtheactualreturnvalueisthe.return_valuepropertyifthemethodisreturnedsuccessfully.


Figure1.MicrosoftRemoteScriptingArchitecture

JSRSArchitectureBrentAshleysJavaScriptremotescriptingaccomplishesthesamegoalusinganiftyDHTMLtrickofinjectingahidden<IFRAME>or<LAYER>(dependingonthebrowsertype)foreachconcurrentremotescriptingcallmade.ThehiddenpieceisnavigatedtotheremotescriptingURLusingHTTPGET.TheresultreturnedfromtheserverisHTMLwithanonLoadJavaScriptcalltothemainwindowcallbackfunction.

Figure2showsthearchitectureofJavaScriptremotescriptingusingaservletontheserver-side.

StepsinvolvedininvokingaremotemethodusingJavaScriptremotescripting:
ThebrowserexecutesaJavaScriptcalltojsrsExecute(thisresidesintheexternaljsrsClient.jsfile[seeResourcestoobtainJSRS]).CodeinjsrsClient.jscreatesan<IFRAME>or<LAYER>(orre-usesanexistingone)andnavigatesittoaURLwiththeappropriateparameters.TheservletreturnsitsHTMLresponseandtheclientreceivesit.The<BODY>onLoadofthereturnedHTMLinvokesthespecifiedcallbackwiththereturnedvalue.


Note:TheexampleinthisarticleshowsMicrosoftsremotescriptingbeingusedsynchronously,butitcouldalsobeusedasynchronouslywithacallbackliketheJSRSexample.However,JSRSisnotcapableofmakingsynchronousmethodinvocations.

Figure2.BrentAshleysJavaScriptremotescriptingarchitecture

LetsseesomecodeTheservletdescribedbelowhasbeendesignedtosupportbothMSRSandJSRS.Thisflexibilitywillbedemonstratedbyallowingtheclienttotogglebetweenusingeithermethod.AsingleHTMLpageiscreatedwithboththeMSRSpieces(JavaScriptandapplet)andtheJSRS(asingleexternalJavaScript)piece.Usingthecategory/subcategoryidea,thegoalistohaveacategoryselectionwhichthendetermineswhichsubcategoryselectionsareavailable.HereistheHTML<BODY>:
Listing1.Categoryselection
<BODYonLoad="javascript:categoryChanged()"><FORMname="form1"><TABLE><TR><TH>RemoteScriptingType:</TH><TD><inputtype="radio"name="clientType"value="MSRS">MSRS<br/><inputtype="radio"name="clientType"value="JSRS"CHECKED>JSRS</TD></TR><TR><TH>Category:</TH><TD><SELECTname="category"onChange="javascript:categoryChanged()"><OPTIONvalue="0"SELECTED>Category0</OPTION><OPTIONvalue="1">Category1</OPTION><OPTIONvalue="2">Category2</OPTION><OPTIONvalue="3">ErrorTest</OPTION></SELECT></TD></TR><TR><TH>Subcategory:</TH><TD><SELECTname="subcategory"><!--Needaplaceholderuntilitcangetloaded--><OPTIONvalue="-1"SELECTED>---------------------</OPTION></SELECT></TD></TR></TABLE></FORM></BODY>

EverythingabouttheHTMLisstraightforward.NotethatcategoryChangediscalledwhenthedocumentisloadedandwhenthecategoryfieldischangedbytheuser.ThecategoryChangedmethodisdefinedas:
Listing2.categoryChangedmethod
functioncategoryChanged(){if(document.form1.clientType[0].checked){//MSRSvarco=RSExecute("/servlet/RSExample","getSubcategories",document.form1.category.options[document.form1.category.selectedIndex].value);if(co.status!=0){return;}varsubcatstr=co.return_value;populateDropDown(subcatstr);}else{//JSRSjsrsExecute("/servlet/RSExample",populateDropDown,"getSubcategories",document.form1.category.options[document.form1.category.selectedIndex].value);}}

RemotescriptingnowcomesintoplaybycallingtheremotemethodgetSubcategories.RefertotheMicrosoftremotescriptingdocumentationfordetailsoftheremotescripting"callobject"returnedfromRSExecute(seeResources).ThecalltojsrsExecutespecifiesthatpopulateDropDownwillbecalledwhentheasynchronouscallcompletes.RefertoResourcesforthedetailsofpopulateDropDown.

Ontheserverside,theservletisdefinedasinListing3.

RSExampleservlethasastaticpublicmethodnamed,notcoincidentally,getSubcategories.Thisimplementationis,ofcourse,simplyaproof-of-concept,butitcouldeasilybeextendedtodoadatabaselookupofthesubcategoriesrelatingtoacategory.NotethatthegetSubcategoriesfunctioncanonlydealwithacatidof0,1,or2.Thesamplecodeincludesademonstrationofinvokingthismethodwithaninvalidvalueof3("ErrorTest"inthecategorydrop-down).Usingremotescriptingisusefulwhenthecategory/subcategorycombinationsaretoonumeroustosendtothebrowserasJavaScriptobjects.Anynumberofmethodscouldbedefinedinthisservletandcalledsimilarlyfromtheclient.

Thesubcategoriesarereturnedtotheclientintheformat"index,value;index,value...."Ideally,thiskindofinformationshouldbepassedusingXML,butinordertomakethisschemebeascross-browserfriendlyaspossible,XMLisnottherightchoice.IftheapplicationenvironmentisconfinedtoInternetExplorer5browsers,thenXMLwouldbeaveryelegantwaytopassinformationwithremotescripting.

Inordertomaketheservletarchitectureasextensibleaspossible,anabstractclassthatextendsHttpServletwaswrittentodispatchthemethodinvocationgenericallyandpackagethereturnvalueinawaytheremotescriptingclient-sidecodeisbuilttohandle.TheHTTPGETmadebyMSRSandJSRSlookslikethecodeinListing4.

BecausetheURLsareuniqueenoughtoallowtheservlettodistinguishbetweenthetwodifferentclient-sidetechniques,asingleabstractservletclasswascreatedthatdynamicallyhandlesbothmethods.Toshowabitofthedetailsofhowthetwoclient-sideremotescriptingmethodsworkinternally;Listing5showstheformatthattheMicrosoftclient-sideremotescriptingpieceisexpectingastheresponsetothatrequest.

AtfirstglanceitwouldappearthatXMLisbeingusedbehindthescenes,butnotethatthevalueoftheTYPEattributeoftheRETURN_VALUEelementisnotdouble-quotedandthereforedoesnotfollowtheXMLspecification.Welljustshakeourheadsatthatapparentoversightandmoveon.TheVERSIONattributeoftheMETHODelementisignoredbytheclient-sidecode,butitwasleftinjusttokeepthingsconsistentwiththereturnvaluesfromMicrosoftsserver-sideimplementationinASP.ThevalueoftheRETURN_VALUEelementisURL-encoded.Thisvalueisunescapedintheclient-sideframeworkautomatically(notespacesreplacedby"%20"ratherthan"+,"asthatishowtheJavaScriptunescapefunctionrequires).Theclient-sideJavaScriptjustusestextfunctionstofindthenecessaryinformationintheresponseandbuildsthe"callobject"accordingly,whichisthenreturnedfromRSExecutetothecallingcode.

TheservletsimilarlybuildstheresponsetoJSRScallsintheformatthatitexpects.ThereturnvalueisshowninListing6.

TheheartofthemethodinvocationoccursinthedoGetmethodofRemoteScriptingServlet(asubclassofHttpServlet).HereistherelevantpartofdoGet:
Listing7.doGet
Stringmethod;intpcount=0;callbackName=request.getParameter("C");if(callbackName!=null){//clientisJSRS-itpassesa"C"parameterclientType=JSRS;method=request.getParameter("F");//JSRSdoesnttellushowmanyparameters,socountthemwhile(request.getParameter("P"+pcount)!=null)pcount++;}else{clientType=MSRS;method=request.getParameter("_method");pcount=Integer.parseInt(request.getParameter("pcount"));}//...somecodeomitted,refertothefullcodeincluded//findandinvoketheappropriatestaticmethodintheconcreteclassClassc=this.getClass();Methodm=c.getMethod(method,paramSpec);returnValue=(String)m.invoke(null,params);

RefertotheincludedcodeforthefullRemoteScriptingServletclass(seeListing8).Firsttheclienttypeisdetermined,keyedoffthe"C"parameterthatispresentforJSRS,butnotforMSRS.ThentheideaistogetareferencetotheClassoftheservletbeinginvoked(RSExample,inthiscase),getareferencetotheMethodbeinginvoked(getSubcategories)basedonthenumberofparameters,andtheninvokethatmethodwiththeappropriateparameters.Theparameterstothedispatchedmethodsmustmatchinnumberwiththecallfromtheclient,andmustallbeoftypeString(internallytothatmethod,theStringscanbeconvertedtoothertypesifnecessary).Dispatchingtostaticmethodswaschosenarbitrarily,butitcouldeasilydispatchtoinstancemethodsratherthanclassmethodsbyspecifying"this"asthefirstparametertoinvoke.Theentirecodeaboveiswrappedinsideatry/catchblock,andanyexceptionthrownwillbegracefullysentbacktotheclient.MSRSerrorsarereturnedbysettingtheTYPEattributeofRETURN_VALUEtoERROR,andspecifyingtheescapederrortextasthevalueofRETURN_VALUE.JSRSerrorsarereturnedasHTMLthatexecutesjsrsErrorintheonLoad.

Nowwhat?Thereareallkindsofinterestingthingsthatcanbeaccomplishedusingremotescripting.TakingadvantageoftheasynchronousfeatureofremotescriptingandJavaScriptwindowtimers,amessagingsystemcouldbebuilttoallowabrowsertopolltheserverformessages,content,orothertypesofupdateinformation.

IssuesBecauseofthetechnologiesusedinremotescripting,therearelimitationsonthenumberofbrowsersitwillworkwith.TouseMSRS,JavaScriptmustcommunicatewiththehiddenapplettoperformtheremotecall.TheJavaVirtualMachine(JVM)isonly"scriptable"(suchthatJavaScriptandJavaappletscancommunicate)onalimitednumberofbrowsers,meaningonlyNetscapeandInternetExploreronWin32(andpossiblyonotherplatforms)cansupportMSRS.BecauseallparametersareencodedintheURLforanHTTPGETrequest,thereisalimitationtothesizeoftheparameters.AmodifiedappletexiststhatdoesHTTPPOSTratherthanGETtoeliminatethislimitation.BrentAshleyssitehasthePOSTversionoftheappletavailablefordownload(seeResources.

Scalabilityissuesariseifremotescriptingisusedforcontinuouspolling.Dependingonanapplicationsneeds,thefrequencyofrequestscanbereducedorevenmadedynamicsuchthatitpollslessfrequentlyifitreceivesfewermessagesandincreasesthefrequencywhenlargersetsofmessagesarereceived.SinceHTTPGETisusedforthemethodcall,thesizeofthedatasenttothemethodisrestricted.Theresponsetoaremotemethodhasnoexplicitsizerestrictionsonsize;however,iflargeamountsofdataperrequestarebeingpassedtoorfromtheserver,thismessagingarchitectureisnotappropriate.

Thesecurityoftheremotescriptingmethodsshouldbeconsidered.BysimplyopeningtheappropriateURLalongwithitsnecessaryparametersinaWebbrowser,theremotemethodisbeingcalledanditsresultsarebeingsentback.Itmaybenecessarytoassurethattheuserisloggedintotheapplicationbeforereturninganyresults.Therearesecurityrestrictionsthatdonotallowabrowsertousecross-hostscripting,sothatthehostforthemainHTMLpagemustbethesameasthehostfortheremotescriptingservlet.

FirewallsarenotanissueforcommunicationsbecauseHTTPisused,althoughinsomeenvironmentsJavaappletsareblockedbyfirewallsthatwouldpreventMicrosoftsremotescriptingfromworking.HTTPSwillalsoworkfinewithbothclient-sidemethods.

ConclusionRemotescriptingisagreattechniqueforcreatingamoredesktop-likefeelforWebbrowser-basedapplications.TheRemoteScriptingServletbaseclassprovidedwiththisarticleopensthedoorforserver-sideJavaapplicationstousetrickspreviouslyonlyavailabletoActiveServerPageapplications.

Resources
ReadMicrosoftsdocumentationonremotescripting.DownloadBrentAshleysJSRS.GetthedetailsofpopulateDropDownDownloadwiththisexamplecode(includingtheRemoteScriptingServletclass).LearnthebeautyofJavasreflectionAPI.ApachesTomcatwasusedtotestthisservlet.

AbouttheauthorErikisthePresidentofeHatcherSolutions,Inc.HealsorecentlyjoinedPromoFuelastheirHighOctaneSiteArchitect.BeingactivelyinvolvedinsoftwaredeveloperorganizationsinTucson,AZ,hehaspresentedonWindowsNTsecurityanalysisattheBackOfficeAdministratorsConferenceandonXMLfortheTucsonDeveloperSeries.Youcanreachhimaterik@hatcher.net.
而学习JAVA我觉得最应该避免的就是:只学习,不思考,只记忆,不实践!
若天明 该用户已被删除
沙发
 楼主| 发表于 2015-7-3 04:59:11 | 显示全部楼层
有时间再研究一下MVC结构(把Model-View-Control分离开的设计思想)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-5-3 16:26

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表