外文翻译-Java的Servlet编程_第1页
外文翻译-Java的Servlet编程_第2页
外文翻译-Java的Servlet编程_第3页
外文翻译-Java的Servlet编程_第4页
外文翻译-Java的Servlet编程_第5页
已阅读5页,还剩6页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

0外文原文JavaServletProgrammingTheServletAlternativeTheservletlifecycleallowsservletenginestoaddressboththeperformanceandresourceproblemsofCGIandthesecurityconcernsoflow-levelserverAPIprogramming.AservletenginemayexecuteallitsservletsinasingleJavavirtualmachine(JVM).BecausetheyareinthesameJVM,servletscanefficientlysharedatawitheachother,yettheyarepreventedbytheJavalanguagefromaccessingoneanothersprivatedata.Servletsmayalsobeallowedtopersistbetweenrequestsasobjectinstances,takingupfarlessmemorythanfull-fledgedprocesses.Beforeweproceedtoofar,youshouldknowthattheservletlifecycleishighlyflexible.Servershavesignificantleewayinhowtheychoosetosupportservlets.Theonlyhardandfastruleisthataservletenginemustconformtothefollowinglifecyclecontract:Createandinitializetheservlet.Handlezeroormoreservicecallsfromclients.Destroytheservletandthengarbagecollectit.Itsperfectlylegalforaservlettobeloaded,created,andinstantiatedinitsownJVM,onlytobedestroyedandgarbagecollectedwithouthandlinganyclientrequestsorafterhandlingjustonerequest.Anyservletenginethatmakesthisahabit,however,probablywontlastlongontheopenmarket.InthischapterwedescribethemostcommonandmostsensiblelifecycleimplementationsforHTTPservlets.ASingleJavaVirtualMachineMostservletengineswanttoexecuteallservletsinasingleJVM.WherethatJVMitselfexecutescandifferdependingontheserver,though.WithaserverwritteninJava,suchastheJavaWebServer,theserveritselfcanexecuteinsideaJVMrightalongsideitsservlets.Withasingle-process,multithreadedwebserverwritteninanotherlanguage,theJVMcanoftenbeembeddedinsidetheserverprocess.HavingtheJVMbepartoftheserverprocessmaximizesperformancebecauseaservletbecomes,inasense,justanotherlow-1levelserverAPIextension.Suchaservercaninvokeaservletwithalightweightcontextswitchandcanprovideinformationaboutrequeststhroughdirectmethodinvocations.Amultiprocesswebserver(whichrunsseveralprocessestohandlerequests)doesntreallyhavethechoicetoembedaJVMdirectlyinitsprocessbecausethereisnooneprocess.ThiskindofserverusuallyrunsanexternalJVMthatitsprocessescanshare.Withthisapproach,eachservletaccessinvolvesaheavyweightcontextswitchreminiscentofFastCGI.Alltheservlets,however,stillsharethesameexternalprocess.Fortunately,fromtheperspectiveoftheservlet(andthusfromyourperspective,asaservletauthor),theserversimplementationdoesntreallymatterbecausetheserveralwaysbehavesthesameway.InstancePersistenceWesaidabovethatservletspersistbetweenrequestsasobjectinstances.Inotherwords,atthetimethecodeforaservletisloaded,theservercreatesasingleclassinstance.Thatsingleinstancehandleseveryrequestmadeoftheservlet.Thisimprovesperformanceinthreeways:Itkeepsthememoryfootprintsmall.Iteliminatestheobjectcreationoverheadthatwouldotherwisebenecessarytocreateanewservletobject.Aservletcanbealreadyloadedinavirtualmachinewhenarequestcomesin,lettingitbeginexecutingrightaway.classesarenotnicelyreloadedlikeservlets.Asupportclass,placedinthedefaultservletsdirectoryandaccessedbyaservlet,isloadedbythesameclassloaderinstancethatloadedtheservlet.Itdoesntgetitsownclassloaderinstance.Consequently,ifthesupportclassisrecompiledbuttheservletreferringtoitisnt,nothinghappens.Theserverchecksonlythetimestamponservletclassfiles.Afrequentlyusedtricktoimproveperformanceistoplaceservletsinthedefaultservletdirectoryduringdevelopmentandmovethemtotheserversclasspathfordeployment.Havingthemoutofthedefaultdirectoryeliminatestheneedlesstimestampcomparisonforeachrequest.InitandDestroy2Justlikeapplets,servletscandefineinit()anddestroy()methods.Aservletsinit(ServletConfig)methodiscalledbytheserverimmediatelyaftertheserverconstructstheservletsinstance.Dependingontheserveranditsconfiguration,thiscanbeatanyofthesetimes:WhentheserverstartsWhentheservletisfirstrequested,justbeforetheservice()methodisinvokedAttherequestoftheserveradministratorInanycase,init()isguaranteedtobecalledbeforetheservlethandlesitsfirstrequest.Theinit()methodistypicallyusedtoperformservletinitialization-creatingorloadingobjectsthatareusedbytheservletinthehandlingofitsrequests.Whynotuseaconstructorinstead?Well,inJDK1.0(forwhichservletswereoriginallywritten),constructorsfordynamicallyloadedJavaclasses(suchasservlets)couldntacceptarguments.So,inordertoprovideanewservletanyinformationaboutitselfanditsenvironment,aserverhadtocallaservletsinit()methodandpassalonganobjectthatimplementstheServletConfiginterface.Also,Javadoesntallowinterfacestodeclareconstructors.Thismeansthatthejavax.servlet.ServletinterfacecannotdeclareaconstructorthatacceptsaServletConfigparameter.Ithastodeclareanothermethod,likeinit().Itsstillpossible,ofcourse,foryoutodefineconstructorsforyourservlets,butintheconstructoryoudonthaveaccesstotheServletConfigobjectortheabilitytothrowaServletException.Itenablespersistence.Aservletcanhavealreadyloadedanythingitslikelytoneedduringthehandlingofarequest.Forexample,adatabaseconnectioncanbeopenedonceandusedrepeatedlythereafter.Itcanevenbeusedbyagroupofservlets.Anotherexampleisashoppingcartservletthatloadsinmemorythepricelistalongwithinformationaboutitsrecentlyconnectedclients.Yetanotherservletmaychoosetocacheentirepagesofoutputtosavetimeifitreceivesthesamerequestagain.Notonlydoservletspersistbetweenrequests,butsodoanythreadscreatedbyservlets.Thisperhapsisntusefulfortherun-of-the-millservlet,butitopensupsomeinterestingpossibilities.Considerthesituationwhereonebackgroundthreadperforms3somecalculationwhileotherthreadsdisplaythelatestresults.Itsquitesimilartoananimationappletwhereonethreadchangesthepictureandanotheronepaintsthedisplay.BackgroundProcessingServletscandomorethansimplypersistbetweenaccesses.Theycanalsoexecutebetweenaccesses.Anythreadstartedbyaservletcancontinueexecutingevenaftertheresponsehasbeensent.Thisabilityprovesmostusefulforlong-runningtaskswhoseincrementalresultsshouldbemadeavailabletomultipleclients.Abackgroundthreadstartedininit()performscontinuousworkwhilerequest-handlingthreadsdisplaythecurrentstatuswithdoGet().Itsasimilartechniquetothatusedinanimationapplets,whereonethreadchangesthepictureandanotherpaintsthedisplay.LastModifiedTimesBynow,weresureyouvelearnedthatservletshandleGETrequestswiththedoGet()method.Andthatsalmosttrue.ThefulltruthisthatnoteveryrequestreallyneedstoinvokedoGet().Forexample,awebbrowserthatrepeatedlyaccessesPrimeSearchershouldneedtocalldoGet()onlyafterthesearcherthreadhasfoundanewprime.Untilthattime,anycalltodoGet()justgeneratesthesamepagetheuserhasalreadyseen,apageprobablystoredinthebrowserscache.Whatsreallyneededisawayforaservlettoreportwhenitsoutputhaschanged.ThatswherethegetLastModified()methodcomesin.Mostwebservers,whentheyreturnadocument,includeaspartoftheirresponseaLast-Modifiedheader.AnexampleLast-Modifiedheadervaluemightbe:Tue,06-May-9815:41:02GMTThisheadertellstheclientthetimethepagewaslastchanged.Thatinformationaloneisonlymarginallyinteresting,butitprovesusefulwhenabrowserreloadsapage.Mostwebbrowsers,whentheyreloadapage,includeintheirrequestanIf-Modified-Sinceheader.ItsstructureisidenticaltotheLast-Modifiedheader:Tue,06-May-9815:41:02GMTThisheadertellstheservertheLast-Modifiedtimeofthepagewhenitwaslastdownloadedbythebrowser.Theservercanreadthisheaderanddetermineifthefilehaschangedsincethegiventime.Ifthefilehaschanged,theservermustsendthenewer4content.Ifthefilehasntchanged,theservercanreplywithasimple,shortresponsethattellsthebrowserthepagehasnotchangedanditissufficienttoredisplaythecachedversionofthedocument.ForthosefamiliarwiththedetailsofHTTP,thisresponseisthe304NotModifiedstatuscode.Thistechniqueworksgreatforstaticpages:theservercanusethefilesystemtofindoutwhenanyfilewaslastmodified.Fordynamicallygeneratedcontent,though,suchasthatreturnedbyservlets,theserverneedssomeextrahelp.Byitself,thebesttheservercandoisplayitsafeandassumethecontentchangeswitheveryaccess,effectivelyeliminatingtheusefulnessoftheLast-ModifiedandIf-Modified-Sinceheaders.TheextrahelpaservletcanprovideisimplementingthegetLastModified()method.Aservletshouldimplementthismethodtoreturnthetimeitlastchangeditsoutput.Serverscallthismethodattwotimes.Thefirsttimetheservercallsitiswhenitreturnsaresponse,sothatitcansettheresponsesLast-Modifiedheader.ThesecondtimeoccursinhandlingGETrequeststhatincludetheIf-Modified-Sinceheader(usuallyreloads),soitcanintelligentlydeterminehowtorespond.IfthetimereturnedbygetLastModified()isequaltoorearlierthanthetimesentintheIf-Modified-Sinceheader,theserverreturnstheNotModifiedstatuscode.Otherwise,theservercallsdoGet()andreturnstheservletsoutput.7Someservletsmayfinditdifficulttodeterminetheirlastmodifiedtime.Forthesesituations,itsoftenbesttousetheplayitsafedefaultbehavior.Manyservlets,however,shouldhavelittleornoproblem.Considerabulletinboardservletwherepeoplepostcarpoolopeningsortheneedforracquetballpartners.Itcanrecordandreturnwhenthebulletinboardscontentswerelastchanged.Evenifthesameservletmanagesseveralbulletinboards,itcanreturnadifferentmodifiedtimedependingontheboardgivenintheparametersoftherequest.HeresagetLastModified()methodforourPrimeSearcherexamplethatreturnswhenthelastprimewasfound.publiclonggetLastModified(HttpServletRequestreq)returnlastprimeModified.getTime()/1000*1000;5Noticethatthismethodreturnsalongvaluethatrepresentsthetimeasanumberofmillisecondssincemidnight,January1,1970,GMT.ThisisthesamerepresentationusedinternallybyJavatostoretimevalues.Thus,theservletusesthegetTime()methodtoretrievelastprimeModifiedasalong.Beforereturningthistimevalue,theservletroundsitdowntothenearestsecondbydividingby1000andthenmultiplyingby1000.AlltimesreturnedbygetLastModified()shouldberoundeddownlikethis.ThereasonisthattheLast-ModifiedandIf-Modified-Sinceheadersaregiventothenearestsecond.IfgetLastModified()returnsthesametimebutwithahigherresolution,itmayerroneouslyappeartobeafewmillisecondslaterthanthetimegivenbyIf-Modified-Since.Forexample,letsassumePrimeSearcherfoundaprimeexactly869127442359millisecondssincethebeginningoftheDiscoDecade.Thisfactistoldtothebrowser,butonlytothenearestsecond:Thu,17-Jul-9709:17:22GMTNowletsassumethattheuserreloadsthepageandthebrowsertellstheserver,viatheIf-Modified-Sinceheader,thetimeitbelievesitscachedpagewaslastmodified:Thu,17-Jul-9709:17:22GMTSomeservershavebeenknowntoreceivethistime,convertittoexactly869127442000milliseconds,findthatthistimeis359millisecondsearlierthanthetimereturnedbygetLastModified(),andfalselyassumethattheservletscontenthaschanged.Thisiswhy,toplayitsafe,getLastModified()shouldalwaysrounddowntothenearestthousandmilliseconds.TheHttpServletRequestobjectispassedtogetLastModified()incasetheservletneedstobaseitsresultsoninformationspecifictotheparticularrequest.Thegenericbulletinboardservletcanmakeuseofthistodeterminewhichboardwasbeingrequested,forexample.1,Doesitseemconfusinghowoneservletinstancecanhandlemultiplerequestsatthesametime?Ifso,itsprobablybecausewhenwepictureanexecutingprogramweoftenseeobjectinstancesperformingthework,invokingeachothersmethodsandsoon.But,althoughthismodelworksforsimplecases,itsnothowthingsactuallywork.Inreality,all6realworkisdonebythreads.Theobjectinstancesarenothingmorethandatastructuresmanipulatedbythethreads.Therefore,iftherearetwothreadsrunning,itsentirelypossiblethatbothareusingthesameobjectatthesametime.2,Oddfactoid:ifcountwerea64-bitlonginsteadofa32-bitint,itwouldbetheoreticallypossiblefortheincrementtobeonlyhalfperformedatthetimeitisinterruptedbyanotherthread.ThisisbecauseJavausesa32-bitwidestack.3,Forthedaredevilsoutthere,heresastuntyoucantrytoforceasupportclassreload.Putthesupportclassintheservletdirectory.Thenconvincetheserveritneedstoreloadtheservletthatusesthesupportclass(recompileitorusetheUnixutilitytouch).Theclassloaderthatreloadstheservletshouldalsoloadthenewversionofthesupportclass.4,TheexactlocationofthecurrentuserdirectorycanbefoundusingSystem.getProperty(user.dir).5,Unlessyouresounluckythatyourservercrasheswhileinthedestroy()method.Inthatcase,youmaybeleftwithapartially-writtenstatefile-garbagewrittenontopofyourpreviousstate.Tobeperfectlysafe,aservletshouldsaveitsstatetoatemporaryfileandthencopythatfileontopoftheofficialstatefileinonecommand.6,Stoppingthreadsusingthestop()methodasshownhereisdeprecatedinJDK1.2infavorofasaferflag-basedsystem,whereathreadmustperiodicallyexamineaflagvariabletodeterminewhenitshouldstop,atwhichpointitcancleanupandreturnfromitsrun()method.SeetheJDKdocumentationfordetails.7,AservletcandirectlysetitsLast-ModifiedheaderinsidedoGet(),usingtechniquesdiscussedinChapter5SendingHTMLInformation.However,bythetimetheheaderissetinsidedoGet(),itstoolatetodecidewhetherornottocalldoGet().7外文翻译Java的Servlet编程Servlet的替代servlet的生命周期允许servlet引擎,以解决双方的性能和资源的CGI的问题和低级服务器API编程的安全问题。一个servlet引擎可以在一个单一的Java虚拟机(JVM)执行其所有servlet。因为他们是在同一个JVM中,Servlet可以有效地互相共享数据,但它们是由Java语言访问彼此的私有数据阻止。Servlet的可能也被允许请求的对象实例之间坚持,占用较全面的进程的内存少得多。在我们开始之前太远,你应该知道,servlet的生命周期具有高度的灵活性。服务器在如何选择支持servlet的显著余地。唯一的硬性规则是,一个servlet引擎必须符合以下生命周期合同:创建并初始化这个servlet。处理来自客户端零个或多个服务调用。破坏的servlet,然后垃圾收集。这是完全合法的一个servlet加载,创建和实例化它自己的JVM,只有被破坏,垃圾不处理任何客户端请求或仅仅处理一个请求后收集。任何Servlet引擎,使得这一个习惯,但是,可能不会在公开市场上持续很长时间。在这一章中,我们描述了最常见和最明智的生命周期的实现HTTP的servlet。一个单一的Java虚拟机大多数servlet引擎要执行的所有servlet在单个JVM。如该JVM本身执行可以根据服务器的不同,虽然。用Java编写的,如JavaWeb服务器,服务器本身可以在里面一个JVM右沿着它的servlet执行的服务器。用另一种语言编写一个单进程,多线程的Web服务器,在JVM通常可以嵌入到服务器进程中。具有JVM是服务器进程的一部分最大限度地提高性能,因为一个servlet而成,在某种意义上说,只是一个低级别的服务器API扩展。这样的服务器可以调用一个servlet一个轻量级上下文切换,并且可以通过直接方法调用提供有关请求的信息。多进程web服务器(运行多个进程来处理请求),并没有真正的选择直接在其过程中嵌入一个JVM,因为没有一个进程。这种服务器通常运行一个外部的JVM,它的进程可以共享。通过这种方法,每个servlet访问包括一个重量级的上下文切换让人联想到的FastCGI的。所有servlet,但是,仍然共享相同的外部进程。幸运的是,从servlet的角度(因此从您的角度来看,作为一个servlet作者),服务器的实现其实并不重要,因为服务器的行为总是以同样的方式。比如持久性我们前面已经说过,servlet的请求作为对象实例之间仍然存在。换句话说,在一个servlet的代码被加载时,服务器创建一个类的实例。这种单一实例处理制成的servlet的每个请求。这提高了在三个方面表现:它使内存占用小。它消除了创建对象的开销,否则将需要创建一个新的Servlet对象。Servlet可以是已经装载在虚拟机中,当一个请求进来,让它开始执行的时候了。它使持久性。一个servlet可以已经加载任何很可能请求的处理过程中所需要的。8例如,一个数据库连接可以打开一次,使用之后反复。它甚至可以使用一组的servlet。另一个例子是购物车的servlet在内存中加载以及有关其最近连接的客户端信息的价目表。然而,另一个servlet可以选择输出缓存整个页面,以节省时间,如果它再次收到了同样的要求。不仅servlet的请求之间持续存在,但这样做所的servlet创建的任何线程。这也许不是径流式的磨servlet的有用的,但它开辟了一些有趣的可能性。考虑其中一个后台线程执行一些计算,而其它线程显示最新的结果的情况。这是相当类似的动画小程序,其中一个线程改变图像,另一个描绘的显示。后台处理Servlet可以做更多的不是简单地访问之间仍然存在。他们还可以访问之间执行。由servlet启动的任何线程可以继续响应已发送,即使执行。这种能力被证明对于长时间运行的任务,其增量的结果应该提供给多个客户最有用的。后台线程在启动的init()进行连续工作,同时请求处理线程显示与的doGet当前状态()。这是一个类似的技术,在动画中使用的小程序,其中一个线程更改图像和其他涂料的显示。上次修改时间到现在为止,我们相信你们已经了解到的servlet处理GET请求的doGet()方法。而这几乎是真实的。完整的事实是,不是每个请求真的需要调用的doGet()。例如,一个Web浏览器访问反复PrimeSearcher应该需要调用doGet()后,方可搜索线程已经找到了新的素数。直到那个时候,任何调用的doGet()只是生成相同页面的用户已经看到,一个页面可能存储在浏览器的缓存。什么是真正需要的是一种让一个servlet报告时,其输出已改变。这其中的的getLastModified()方法的用武之地。类不好听重装如servlet。的辅助类,放在默认的servlet目录,并通过servlet访问,是由加载该servlet相同的类加载器实例加载。它没有得到自己的类加载器的实例。因此,如果支持类被重新编译,但在servlet指的不是,什么也不会发生。服务器会检查servlet类文件只有时间戳。经常使用的伎俩来提高性能,是把默认的servlet的servlet目录在开发过程中,将它们移动到部署的服务器的类路径中。让他们出了默认目录,消除了为每个请求不必要的时间戳比较。init和destroy就像小程序,Servlet可以定义的init()和destroy()方法。一个servlet的init(ServletConfig)方法被调用的服务器的服务器构建servlet的实例之后。根据不同的服务器及其配置上,这可以在任何一个时代:当服务器启动当servlet第一次被请求,就在服务之前()方法被调用在服务器管理员的请求在任何情况下,init()中保证之前,该servlet处理它的第一个请求被调用。在init()方法通常用于执行servlet初始化-创建或加载那些在其请求的处理所使用的servlet的对象。为什么不使用构造函数来代替?那么,在JDK1.0(为此servlet的最初写的),构造函数动态加载Java类(如Servlet)不能接受的论点。因此,为了提供一个新的servlet有关本身及其环境的信息,服务器不得不调用servlet的init()方法,并沿着一个对象,它实现了ServletConfig接口传递。此外,Java不允许接口来声明构造函数。这意味着,javax.servlet.Servlet接口不能声明一个接受ServletConfig参数的构造函数。它有权宣布另一种方法,如init()中。它仍然是可能的,当然,对9于您定义的构造函数为你的servlet,但在构造函数中你没有访问ServletConfig对象或抛出一个ServletException的能力。大多数的web服务器,当他们返回一个文档,包括作为其响应Last-Modified头的一部分。一个例子Last-Modified头值可能是:周二,06月9815:41:02GMT这个头告诉当时的页面最后修改客户端。单单这些信息只是勉强有趣,但是当一个浏览器重新载入页面也证明是有用的。大多数Web浏览器,当它们重新加载页面,包括在他们的要求一个If-Modified-Since头。它的结构是相同的Last-Modified头:周二,06月9815:41:02GMT这个头告诉服务器页面的最后修改时间,当它是最后一个通过浏览器下载。服务器可以读取该头,并确定文件是否因为在给定时间改变。如果文件已经改变,服务器必须发送新的内容。如果文件没有改变,服务器可以用一个简单的,短的响应,它告诉页面没有改变浏览器和它足以重新显示该文件的缓存版本回复。对于那些熟悉HTTP的细节,这个响应是304“未修改”状态码。这种技术的伟大工程的静态页面:服务器可以使用文件系统来找出当任何文件的最后修改。对于动态生成的内容,不过,如由Servlet返回的,服务器需要一些额外的帮助。就其本身而言,最好的服务器可以做的就是发挥它的安全,并承担与每一个访问的内容的变化,有效地消除了实用性的Last-Modified和If-Modified-Since的头。额外的帮助一个servlet可以提供正在实施的getLastModified()方法。一个servlet应该实现此方法,返回它最后改变了输出的时间。服务器调用此方法的两倍。第一次的服务器调用它时,它返回一个响应,这样就可以设置响应的Last-Modified头。第二次发生在处理GET请求,其中包括了If-Modified-Since头(通常是重载),因此它可以智能地决定如何应对。如果返回的的的getLastModified时间()等于或早于了If-Modified-Since头发送的时间,服务器将返回“未修改”状态码。否则,服务器调用doGet()和返回Servlet的输出。7servlet的一些可能会发现很难确定他们的最后修改时间。对于这些情况,它往往是最好使用“明哲保身”的默认行为。许多servlet的,但是,应该有很少或没有

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论