仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 2383|回复: 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-1-20 09:47:36 | 只看该作者
吧,现在很流行的Structs就是它的一种实现方式,不过Structs用起来实在是很繁,我们只要学习其精髓即可,我们完全可以设计自己的MVC结构。然后你再研究一下软件Refactoring (重构)和极限XP编程,相信你又会上一个台阶。 做完这些,你不如整理一下你的Java代码,把那些经典的程序和常见的应用整理出来,再精心打造一番,提高其重用性和可扩展性。你再找几个志同道合的朋友成立一个工作室吧
不帅 该用户已被删除
板凳
发表于 2015-1-29 06:38:01 | 只看该作者
Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。
小妖女 该用户已被删除
地板
发表于 2015-2-5 20:49:45 | 只看该作者
[url]http://www.jdon.com/[/url]去下载,或到同济技术论坛的服务器[url]ftp://nro.shtdu.edu.cn[/url]去下,安装上有什么问题,可以到论坛上去提问。
愤怒的大鸟 该用户已被删除
5#
发表于 2015-2-13 08:47:45 | 只看该作者
是一种将安全性(Security)列为第一优先考虑的语言
柔情似水 该用户已被删除
6#
发表于 2015-3-3 18:17:13 | 只看该作者
你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢?
灵魂腐蚀 该用户已被删除
7#
发表于 2015-3-11 12:14:30 | 只看该作者
是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言
活着的死人 该用户已被删除
8#
发表于 2015-3-12 16:35:46 | 只看该作者
当然你也可以参加一些开源项目,一方面可以提高自己,另一方面也是为中国软件事业做贡献嘛!开发者在互联网上用CVS合作开发,用QQ,MSN,E-mail讨论联系,天南海北的程序员分散在各地却同时开发同一个软件,是不是很有意思呢?
深爱那片海 该用户已被删除
9#
发表于 2015-3-19 23:57:47 | 只看该作者
那么我书也看了,程序也做了,别人问我的问题我都能解决了,是不是就成为高手了呢?当然没那么简单,这只是万里长征走完了第一步。不信?那你出去接一个项目,你知道怎么下手吗,你知道怎么设计吗,你知道怎么组织人员进行开发吗?你现在脑子里除了一些散乱的代码之外,可能再没有别的东西了吧!
简单生活 该用户已被删除
10#
发表于 2015-3-21 19:59:39 | 只看该作者
Jive的资料在很多网站上都有,大家可以找来研究一下。相信你读完代码后,会有脱胎换骨的感觉。遗憾的是Jive从2.5以后就不再无条件的开放源代码,同时有licence限制。不过幸好还有中国一流的Java程序员关注它,外国人不开源了,中国人就不能开源吗?这里向大家推荐一个汉化的Jive版本—J道。Jive(J道版)是由中国Java界大名 鼎鼎的banq在Jive 2.1版本基础上改编而成, 全中文,增加了一些实用功能,如贴图,用户头像和用户资料查询等,而且有一个开发团队在不断升级。你可以访问banq的网站
分手快乐 该用户已被删除
11#
发表于 2015-4-15 11:40:54 | 只看该作者
Java 编程语言的风格十分接近C、C++语言。
第二个灵魂 该用户已被删除
12#
发表于 2015-4-16 08:11:16 | 只看该作者
Java语言支持Internet应用的开发,在基本的Java应用编程接口中有一个网络应用编程接口(java net),它提供了用于网络应用编程的类库,包括URL、URLConnection、Socket、ServerSocket等。Java的RMI(远程方法激活)机制也是开发分布式应用的重要手段。
飘飘悠悠 该用户已被删除
13#
发表于 2015-4-21 05:23:27 | 只看该作者
不过,每次的执行编译后的字节码需要消耗一定的时间,这同时也在一定程度上降低了 Java 程序的运行效率。
变相怪杰 该用户已被删除
14#
发表于 2015-5-4 04:05:43 | 只看该作者
是一种使网页(Web Page)产生生动活泼画面的语言
谁可相欹 该用户已被删除
15#
发表于 2015-5-11 20:00:26 | 只看该作者
我大二,Java也只学了一年,觉得还是看thinking in java好,有能力的话看英文原版(中文版翻的不怎么好),还能提高英文文档阅读能力。
精灵巫婆 该用户已被删除
16#
发表于 2015-6-11 10:02:39 | 只看该作者
是一种简化的C++语言 是一种安全的语言,具有阻绝计算机病毒传输的功能
admin 该用户已被删除
17#
发表于 2015-6-19 21:59:12 | 只看该作者
Jive的资料在很多网站上都有,大家可以找来研究一下。相信你读完代码后,会有脱胎换骨的感觉。遗憾的是Jive从2.5以后就不再无条件的开放源代码,同时有licence限制。不过幸好还有中国一流的Java程序员关注它,外国人不开源了,中国人就不能开源吗?这里向大家推荐一个汉化的Jive版本—J道。Jive(J道版)是由中国Java界大名 鼎鼎的banq在Jive 2.1版本基础上改编而成, 全中文,增加了一些实用功能,如贴图,用户头像和用户资料查询等,而且有一个开发团队在不断升级。你可以访问banq的网站
山那边是海 该用户已被删除
18#
发表于 2015-7-2 03:58:51 | 只看该作者
如果要向java web方向发展也要吧看看《Java web从入门到精通》学完再到《Struts2.0入门到精通》这样你差不多就把代码给学完了。有兴趣可以看一些设计模块和框架的包等等。
若天明 该用户已被删除
19#
 楼主| 发表于 2015-7-3 04:59:11 | 只看该作者
有时间再研究一下MVC结构(把Model-View-Control分离开的设计思想)
莫相离 该用户已被删除
20#
发表于 2015-7-4 15:30:18 | 只看该作者
所以现在应用最广泛又最好学的就是J2EE了。 J2EE又包括许多组件,如Jsp,Servlet,JavaBean,EJB,JDBC,JavaMail等。要学习起来可不是一两天的事。那么又该如何学习J2EE呢?当然Java语法得先看一看的,I/O包,Util包,Lang包你都熟悉了吗?然后再从JSP学起。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

GMT+8, 2024-4-20 12:06

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

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