外文翻译-将Servlet和JSP组合使用_第1页
外文翻译-将Servlet和JSP组合使用_第2页
外文翻译-将Servlet和JSP组合使用_第3页
外文翻译-将Servlet和JSP组合使用_第4页
外文翻译-将Servlet和JSP组合使用_第5页
已阅读5页,还剩8页未读 继续免费阅读

下载本文档

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

文档简介

0外文原文CombiningJSPandServletsThetechnologyofJSPandServletisthemostimportanttechnologywhichuseJavatechnologytoexploitrequestofserver,anditisalsothestandardwhichexploitbusinessapplication.Javadevelopersprefertouseitforavarietyofreasons,oneofwhichisalreadyfamiliarwiththeJavalanguageforthedevelopmentofthistechnologyareeasytolearnJavatotheotherisapreparation,runeverywheretobringtheconceptofWebapplications,Toachieveaone-preparedeverywhererealized.Andmoreimportantly,iffollowedsomeoftheprinciplesofgooddesign,itcanbesaidofseparatingandcontenttocreatehigh-quality,reusable,easytomaintainandmodifytheapplication.Forexample,ifthedocumentinHTMLembeddedJavacodetoomuch(script),willleadthedevelopedapplicationisextremelycomplex,difficulttoread,itisnoteasyreuse,butalsoforfuturemaintenanceandmodificationwillalsocausedifficulties.Infact,CSDNtheJSP/Servletforum,canoftenseesomequestions,thecodeisverylong,canlogicisnotveryclear,alargenumberofHTMLandJavacodemixedtogether.Thisistherandomdevelopmentofthedefects.EarlydynamicpagesmainlyCGI(CommonGatewayInterface,publicGatewayInterface)technology,youcanusedifferentlanguagesoftheCGIprograms,suchasVB,C/C+orDelphi,andsoon.ThoughthetechnologyofCGIisdevelopedandpowerful,becauseofdifficultiesinprogramming,andlowefficiency,modifycomplexshortcomings,itisgraduallybeingreplacedbythetrend.Ofallthenewtechnology,JSP/Servletwithmoreefficientandeasytoprogram,morepowerful,moresecureandhasagoodportability,theyhavebeenmanypeoplebelievethatthefutureisthemostdynamicsiteofthefuturedevelopmentoftechnology.SimilartoCGI,Servletsupportrequest/responsemodel.Whenacustomersubmitarequesttotheserver,theserverpresentedtherequestServlet,Servletresponsibleforhandlingrequestsandgeneratearesponse,andthengavetheserver,andthenfromtheserversenttothecustomer.AndtheCGIisdifferent,Servletnotgenerateanewprocess,butwithHTTPServeratthesameprocess.Itthreadsthroughtheuseoftechnology,reducetheservercosts.Servlethandlingoftherequestprocessisthis:Whenreceivedfromtheclientsrequest,callingservicemethods,themethodofServletarrivalofthefirstjudgementiswhattypeofrequest(GET/POST/HEAD),thencallstheappropriatetreatment(DoGet/doPost/doHead)andgeneratearesponse.1Althoughsuchacomplex,infact,simplysaidtoServletisaJavaclass.AndthegeneralcategoryofthedifferenceisthatthistypeoperatinginaServletcontainer,whichcanprovidesessionmanagementandtargetedlife-cyclemanagement.SothatwhenyouusetheServlet,youcangetallthebenefitsoftheJavaplatform,includingthesafetyofthemanagement,useJDBCaccessthedatabaseandcross-platformcapability.Moreover,Servletusingthread,andcandevelopmoreefficientWebapplications.JSPtechnologyisakeyJ2EEtechnology,itatahigherlevelofabstractionofaServlet.ItallowsconventionalstaticanddynamicHTMLcontentgeneratedbycombininganHTMLpagelookslike,butasaServlettorun.TherearemanycommercialapplicationserversupportJSPtechnology,suchasBEAWebLogic,IBMWebSphere,JRun,andsoon.JSPandServletusemorethansimple.IfyouhaveaJSPsupportforWebservers,andaJSPdocument,youcanputitFangdaoanystaticHTMLfilescanbeplaced,donothavetocompile,donothavetopack,donothavetoClassPathsettings,youcanvisitasordinaryWebItdidvisit,theserverwillautomaticallyhelpyoutodootherwork.JSPdocumentlookslikeanordinarystaticHTMLdocument,butinsidecontainsanumberofJavacode.Ituses.Jspthesuffix,usedtotelltheserverthisdocumentinneedofspecialtreatment.WhenwevisitaJSPpage,thedocumentwillfirstbetranslatedintoaJSPengineJavasourcefiles,isactuallyaServlet,andcompiler,andthen,likeotherServlet,fromServletenginetohandle.Servletengineofthistypeloading,handlingrequestsfromcustomers,andtheresultsreturnedtothecustomer,asshownbelow:Figure1:CallingtheprocessofJSPpagesAfteranothervisitthispagetothecustomer,aslongasthepapertherehavebeennochanges,JSPenginehasbeenloadeddirectlycalltheServlet.Ifyouhavealreadybeenmodified,itwillbeonceagaintheimplementationoftheaboveprocess,translate,compileandload.Infact,thisistheso-calledfirstpersontopunishment.Becausewhenthefirstvisittotheimplementationofaseriesoftheaboveprocess,sowillspendsometimeaftersuchavisitwouldnot.2JavaservletsofferapowerfulAPIthatprovidesaccesstoalltheinformationabouttherequest,thesession,biningJSPwithservletsletsyouclearlyseparatetheapplicationlogicfromthepresentationoftheapplication;inotherwords,itletsyouusethemostappropriatecomponenttypefortherolesofModel,ViewandController.Servlets,Filters,andListenersAservletisaJavaclassthatextendsaserverwithfunctionalityforprocessingarequestandproducingaresponse.ItsimplementedusingtheclassesandinterfacesdefinedbytheServletAPI.TheAPIconsistsoftwopackages:thejavax.servletpackagecontainsclassesandinterfacesthatareprotocol-independent,whilethejavax.servlet.httppackageprovidesHTTP-specificextensionsandutilityclasses.Whatmakesaservletaservletisthattheclassimplementsaninterfacenamedjavax.servlet.Servlet,eitherdirectlyorbyextendingoneofthesupportclasses.Thisinterfacedefinesthemethodsusedbythewebcontainertomanageandinteractwiththeservlet.AservletforprocessingHTTPrequeststypicallyextendsthejavax.servlet.http.HttpServletclass.ThisclassimplementstheServletinterfaceandprovidesadditionalmethodssuitableforHTTPprocessing.ServletLifecycleThewebcontainermanagesallaspectsoftheservletslifecycle.Itcreatesaninstanceoftheservletclasswhenneeded,passesrequeststotheinstanceforprocessing,andeventuallyremovestheinstance.ForanHttpServlet,thecontainercallsthefollowingmethodsattheappropriatetimesintheservletlifecycle.BesidesthedoGet()anddoPost()methods,therearemethodscorrespondingtotheotherHTTPmethods:doDelete(),doHead(),doOptions(),doPut(),anddoTrace().Typicallyyoudontimplementthesemethods;theHttpServletclassalreadytakescareofHEAD,OPTIONS,andTRACErequestsinawaythatssuitableformostservlets,andtheDELETEandPUTHTTPmethodsarerarelyusedinawebapplication.Itsimportanttorealizethatthecontainercreatesonlyoneinstanceofeachservlet.Thismeansthattheservletmustbethreadsafe-abletohandlemultiplerequestsatthesametime,eachexecutingasaseparatethreadthroughtheservletcode.Withoutgettinglostindetails,yousatisfythisrequirementwithregardstoinstancevariablesifyoumodifythereferencedobjectsonlyintheinit()anddestroy()methods,andjustreadthemintherequestprocessingmethods.CompilingandInstallingaServlet3Tocompileaservlet,youmustfirstensurethatyouhavetheJARfilecontainingallServletAPIclassesintheCLASSPATHenvironmentvariable.TheJARfileisdistributedwithallwebcontainers.Tomcatincludesitinafilecalledservlet.jar,locatedinthecommon/libdirectory.OnaWindowsplatform,youincludetheJARfileintheCLASSPATH.ReadingaRequestOneoftheargumentspassedtothedoGet()anddoPost()methodsisanobjectthatimplementstheHttpServletRequestinterface.Thisinterfacedefinesmethodsthatprovideaccesstoawealthofinformationabouttherequest.GeneratingaResponseBesidestherequestobject,thecontainerpassesanobjectthatimplementstheHttpServletResponseinterfaceasanargumenttothedoGet()anddoPost()methods.Thisinterfacedefinesmethodsforgettingawriterorstreamfortheresponsebody.Italsodefinesmethodsforsettingtheresponsestatuscodeandheaders.UsingFiltersandListenersTheservletspecificationdefinestwocomponenttypesbesideservlets:filtersandlisteners.ThesetwotypeswereintroducedintheServlet2.3specification,soifyoureusingacontainerthatdoesntyetsupportthisversionofthespecification,Imafraidyoureoutofluck.FiltersAfilterisacomponentthatcaninterceptarequesttargetedforaservlet,JSPpage,orstaticpage,aswellastheresponsebeforeitssenttotheclient.Thismakesiteasytocentralizetasksthatapplytoallrequests,suchasaccesscontrol,logging,andchargingforthecontentortheservicesofferedbytheapplication.Afilterhasfullaccesstothebodyandheadersoftherequestandresponse,soitcanalsoperformvarioustransformations.OneexampleiscompressingtheresponsebodyiftheAccept-Languagerequestheaderindicatesthattheclientcanhandleacompressedresponse.AfiltercanbeappliedtoeitheraspecificservletortoallrequestsmatchingaURLpattern,suchasURLsstartingwiththesamepathelementsorhavingthesameextension.ListenersListenersallowyourapplicationtoreacttocertainevents.PriortoServlet2.3,youcouldhandleonlysessionattributebindingevents(triggeredwhenanobjectwasaddedorremovedfromasession).Youcoulddothisbylettingtheobjectsavedasasessionattribute(usingthe4HttpSession.setAttribute()method)implementtheHttpSessionBindingListenerinterface.Withthenewinterfacesintroducedinthe2.3versionofthespecification,youcancreatelistenersforservletcontextandsessionlifecycleeventsaswellassessionactivationandpassivationevents(usedbyacontainerthattemporarilysavessessionstatetodiskormigratesasessiontoanotherserver).Anewsessionattributeeventlisteneralsomakesitpossibletodealwithattributebindingeventsforallsessionsinoneplace,insteadofplacingindividuallistenerobjectsineachsession.ThenewtypesoflistenersfollowthestandardJavaeventmodel.Inotherwords,alistenerisaclassthatimplementsoneormoreofthelistenerinterfaces.Theinterfacesdefinemethodsthatcorrespondtoevents.Thelistenerclassisregisteredwiththecontainerwhentheapplicationstarts,andthecontainerthencallstheeventmethodsattheappropriatetimes.InitializingSharedResourcesUsingaListenerBeanslikethistypicallyneedtobeinitializedbeforetheycanbeused.Forinstance,theymayneedareferencetoadatabaseorsomeotherexternaldatasourceandmaycreateaninitialinformationcacheinmemorytoprovidefastaccesseventothefirstrequestfordata.YoucanincludecodeforinitializationofthesharedresourcesintheservletandJSPpagesthatneedthem,butamoremodularapproachistoplaceallthiscodeinoneplaceandlettheotherpartsoftheapplicationworkontheassumptionthattheresourcesarealreadyinitializedandavailable.Anapplicationlifecyclelistenerisaperfecttoolforthistypeofresourceinitialization.Thistypeoflistenerimplementsthejavax.servlet.ServletContextListenerinterface,withmethodscalledbythecontainerwhentheapplicationstartsandwhenitshutsdown.PickingtheRightComponentTypeforEachTaskTheProjectBillboardapplicationintroducedisafairlycomplexapplication.Halfthepagesarepurecontrollerandbusinesslogicprocessing,itaccessesadatabasetoauthenticateusers,andmostpagesrequireaccesscontrol.Inreallife,itwouldlikelycontainevenmorepages,forinstance,pagesforaccesstoashareddocumentarchive,timeschedules,andasetofpagesforadministration.Astheapplicationevolves,itmaybecomehardtomaintainasapureJSPapplication.Itseasytoforgettoincludetheaccesscontrolcodeinnewpages.ThisisclearlyanapplicationthatcanbenefitfromusingacombinationofJSPpagesandthecomponenttypesdefinedbytheservletspecificationfortheMVCroles.Letslookatthemainrequirementsandseehowwecanmapthemtoappropriatecomponenttypes:Databaseaccessshouldbeabstracted,toavoidknowledgeofaspecificdataschema5ordatabaseengineinmorethanonepartoftheapplication:beansintheroleofModelcanbeusedtoaccomplishthis.Thedatabaseaccessbeansmustbemadeavailabletoallotherpartsoftheapplicationwhenitstarts:anapplicationlifecycleeventlisteneristheperfectcomponenttypeforthistask.Onlyauthenticatedusersmustbeallowedtousetheapplication:afiltercanperformaccesscontroltosatisfythisrequirement.RequestprocessingisbestdonewithJavacode:aservlet,actingastheController,fitsthebill.Itmustbeeasytochangethepresentation:thisiswhereJSPshines,actingastheView.Addingservlets,listeners,andfilterstothemixminimizestheneedforcomplexlogicintheJSPpages.PlacingallthiscodeinJavaclassesinsteadmakesitpossibletousearegularJavacompileranddebuggertofixpotentialproblems.CentralizedRequestProcessingUsingaServletWithaservletasthecommonentrypointforallapplicationrequests,yougaincontroloverthepageflowoftheapplication.Theservletcandecidewhichtypeofresponsetogeneratedependingontheoutcomeoftherequestedaction,suchasreturningacommonerrorpageforallrequeststhatfail,ordifferentresponsesdependingonthetypeofclientmakingtherequest.Withthehelpfromsomeutilityclasses,itcanalsoprovideservicessuchasinputvalidation,I18Npreparations,andingeneral,encourageamorestreamlinedapproachtorequesthandling.WhenyouuseaservletasaController,youmustdealwiththefollowingbasicrequirements:AllrequestsforprocessingmustbepassedtothesingleControllerservlet.Theservletmustbeabletodistinguishrequestsfordifferenttypesofprocessing.Hereareotherfeaturesyouwillwantsupportfor,eventhoughtheymaynotberequirementsforallapplications:Astrategyforextendingtheapplicationtosupportnewtypesofprocessingrequestsinaflexiblemanner.Amechanismforchangingthepageflowoftheapplicationwithoutmodifyingcode.MappingApplicationRequeststotheServletThefirstrequirementforusingaControllerservletisthatallrequestsmustpassthrough6it.Thiscanbesatisfiedinmanyways.Ifyouhaveplayedaroundabitwithservletspreviously,youreprobablyusedtoinvokingaservletwithaURIthatstartswith/myApp/servlet.ThisisaconventionintroducedbySunsJavaWebServer(JWS),thefirstproducttosupportservletsbeforetheAPIwasstandardized.Mostservletcontainerssupportthisconventiontoday,eventhoughitsnotformallydefinedintheservletspecification.7中文翻译将Servlet和JSP组合使用Servlet和JSP技术是用Java开发服务器端应用的主要技术,是开发商务应用表示端的标准。Java开发者喜欢使用它有多种原因,其一是对于已经熟悉Java语言的开发者来说这个技术容易学习;其二是Java把“一次编写,到处运行”的理念带入到Web应用中,实现了“一次编写,到处实现”。而且更为重要的是,如果遵循一些良好的设计原则的话,就可以把表示和内容相分离,创造出高质量的、可以复用的、易于维护和修改的应用程序。比方说,在HTML文档中如果嵌入过多的Java代码(scriptlet),就会导致开发出来的应用非常复杂、难以阅读、不容易复用,而且对以后的维护和修改也会造成困难。事实上,在CSDN的JSP/Servlet论坛中,经常可以看到一些提问,代码很长,可以逻辑却不是很清晰,大量的HTML和Java代码混杂在一起,让人看得一头雾水。这就是随意开发的弊端。早期的动态网页主要采用CGI(CommonGatewayInterface,公共网关接口)技术,你可以使用不同的语言编写CGI程序,如VB、C/C+或Delphi等。虽然CGI技术发展成熟且功能强大,但由于编程困难、效率低下、修改复杂等缺点,所以有逐渐被取代的趋势。在所有的新技术中,JSP/Servlet具备更高效、更容易编程、功能更强、更安全和具有良好的可移植性,因而被许多人认为是未来最有发展前途的动态网站技术。与CGI相似,Servlet支持请求/响应模型。当一个客户向服务器递交一个请求时,服务器把请求送给Servlet,Servlet负责处理请求并生成响应,然后送给服务器,再由服务器发送给客户。与CGI不同的是,Servlet没有生成新的进程,而是与HTTPServer处于同一进程中。它通过使用线程技术,减小了服务器的开销。Servlet处理请求的过程是这样的:当收到来自客户端的请求后,调用service方法,该方法中Servlet先判断到来的请求是什么类型的(GET/POST/HEAD),然后调用相应的处理方法(doGet/doPost/doHead)并生成响应。别看这么复杂,其实简单说来Servlet就是一个Java类。与一般类的不同之处是,这个类运行在一个Servlet容器内,可以提供session管理和对象生命周期管理。因而当你使用Servlet的时候,你可以得到Java平台的所有好处,包括安全性管理、使用JDBC访问数据库以及跨平台的能力。而且,Servlet使用线程,因而可以开发出效率更高的Web应用。JSP技术是J2EE的一个关键技术,它在更高一级的层次上抽象Servlet。它可以让常规静态HTML与动态产生的内容相结合,看起来像一个HTML网页,却作为Servlet来运行。现在有许多商业应用服务器支持JSP技术,比如BEAWebLogic、IBMWebSphere、JRun等等。使用JSP比用Servlet更简单。如果你有一个支持JSP的Web服务器,并且有一个JSP文件,你可以把它放倒任何静态HTML文件可以放置的位置,不用编译,不用打包,也不用进行ClassPath的设置,就可以像访问普通网页那样访问它,服务器会自动帮你做好其他的工作。JSP文件看起来就像一个普通静态HTML文件,只不过里面包含了一些Java代码。它使用.jsp的后缀,用来告诉服务器这个文件需要特殊的处理。当我们访问一个JSP页面的时候,这个文件首先会被JSP引擎翻译为一个Java源文件,8其实就是一个Servlet,并进行编译,然后像其他Servlet一样,由Servlet引擎来处理。Servlet引擎装载这个类,处理来自客户的请求,并把结果返回给客户,如下图所示:图1:调用JSP页面的流程以后再有客户访问这个页面的时候,只要该文件没有发生过更改,JSP引擎就直接调用已经装载的Servlet。如果已经做过修改的话,那就会再次执行以上过程,翻译、编译并装载。其实这就是所谓的“第一人惩罚”。因为首次访问的时候要执行一系列以上的过程,所以会耗费一些时间;以后的访问就不会这样了。Javaservlet提供了一种强有力的API,用这个API可以访问关于请求、会话和应用程序的所有信息。将servlet和JSP页面组合起来使用,可以把应用程序的逻辑部分和外观呈现部分清楚地分开;换句话,利用这个方式可以对模型、视图和控制器这三种角色分别使用最合适的组件类型。Servlet、过滤器和监听器Servlet是一种Java类,它使得服务器的功能可扩展至处理请求和生成应答。它是用ServletAPI定义的类和接口实现的。API由两个程序包组成:jvavax.servlet程序包包含独立于协议的类和接口,而javax.servlet.http程序包则提供HTTP特定的扩展的实用程序类。Servlet的实质是实现了接口javax.servlet.Servlet的类,实现是直接完成或通过扩展某个支持类来完成的。该接口定义了Web容器用来管理servlet和与之交互的方法。用于处理HTTP请求的servlet一般情况下都会扩展javax.servlet.http.HttpServlet类。该类实现了Servlet接口,并提供了使用HTTP处理的附加方法。Servlet的生命周期Web容器管理servlet生命周期的所有方面。它根据需要创建servlet类的实例、将请求传递给实例进行处理,最终删除实例。对于HttpServlet来说,容器会在servlet生命周期的适当时间调用方法。除了doGet()和doPost()方法之外,还有一些对应于其他HTTP方法的9方法:doDelete()、doHead()、doOptiongs()、doPut()和doTrace()。一般情况下不用实现这些方法,因为HttpServlet类已经用适用于大多数servlet的方法考虑到了HEAD、OPTIONS和TRACE请求,而且DELETE和PUT这两种HTTP方法很少用在Web应用程序中。容器只为每个Servlet创建一个实例非常重要。这意味着servlet必须是线程安全的即,能够同时处理多个请求,每个处理都通过servlet代码作为单独的线程来执行。如果只在init()和destroy()方法中修改参考的对象,而且只在请求处理方法中读取他们,那么不用丧失任何细节就可以满足关于实例变量的这个要求。编译和安装servlet要编译servlet,必须首先确保JAR文件包含着CLASSPATH环境变量中所有ServletAPI类。该JAR文件将随所有的Web容器一起发布。Tomcat中包含了一个名为servlet.jar的JAR文件,位于common/lib目录中。在Windows平台中,应在CLASSPATH中包含JAR文件。读取请求传递到doGet()和doPost()方法的参数之一是实现了HttpServletRequest接口的对象。该接口定义的方法可提供对关于请求的许多信息的访问。生成应答除应答对象之外,容器还将实现HttpServletRequest接口的对象作为icanshu传递给doGet()和doPost()方法。该接口定义了为应答行为体获取数序程序或流的方法。它还定义了设置应答状态代码和首部的方法。使用过滤器和监听器Servlet规范servlet内定义了两种组件类型:过滤器和监听器。这两种类型是在Servlet2.3规范中引入的,因此,如果你使用的是不支持该版本规范的容器,恐怕就不能继续学习了。过滤器过滤器是一种组件,可以解释对servlet、JSP页面或静态页面的请求以及发送给客户端之前的应答。这样可以很容易地将应用于所有请求的任务集中在一起,例如访问控制、登录和内容的开销或应用提供的服务等。过滤器对请求与应答的行为体和首部具有完全访问权限,因此还可以执行各种转换。例如,如果Accept-Language请求首部指出客户端可以处理压缩的应答,那么过滤器就可以压缩应答的行为体。过滤器可以应用在特定servlet上,或匹配某种URL模式的所有请求上,例如以相同的路径元素开头或具有相同扩展名的URL。监听器监听器允许应用程序对特定事件做出回应。Servlet2.3之前,只能处理会话属性绑定事件(在添加对象或从会话中删除对象时)。实现监听器的方式是用保存为会话属性(使用HttpSession.setAttribute()方法)的对象实现HttpSessionBinding-Listener接口。随着Servlet规范的2.3版本中新接

温馨提示

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

评论

0/150

提交评论