外文翻译 - Servlet 与JSP核心编程_第1页
外文翻译 - Servlet 与JSP核心编程_第2页
外文翻译 - Servlet 与JSP核心编程_第3页
外文翻译 - Servlet 与JSP核心编程_第4页
外文翻译 - Servlet 与JSP核心编程_第5页
已阅读5页,还剩11页未读 继续免费阅读

下载本文档

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

文档简介

0ANOVERVIEWOFSERVLETANDJSPTECHNOLOGYChap1ANOVERVIEWOFSERVLETANDJSPTECHNOLOGY1.1AServletsJobServletsareJavaprogramsthatrunonWeborapplicationservers,actingasamiddlelayerbetweenrequestscomingfromWebbrowsersorotherHTTPclientsanddatabasesorapplicationsontheHTTPserver.1.Readtheexplicitdatasentbytheclient.TheendusernormallyentersthisdatainanHTMLformonaWebpage.However,thedatacouldalsocomefromanappletoracustomHTTPclientprogram.Chapter4discusseshowservletsreadthisdata.2.ReadtheimplicitHTTPrequestdatasentbythebrowser.ItshowsasinglearrowgoingfromtheclienttotheWebserver(thelayerwhereservletsandJSPexecute),buttherearereallytwovarietiesofdata:theexplicitdatathattheenduserentersinaformandthebehind-the-scenesHTTPinformation.Bothvarietiesarecritical.TheHTTPinformationincludescookies,informationaboutmediatypesandcompressionschemesthebrowserunderstands,andsoforth;itisdiscussedinChapter5.3.Generatetheresults.Thisprocessmayrequiretalkingtoadatabase,executinganRMIorEJBcall,invokingaWebservice,orcomputingtheresponsedirectly.Yourrealdatamaybeinarelationaldatabase.Fine.ButyourdatabaseprobablydoesntspeakHTTPorreturnresultsinHTML,sotheWebbrowsercanttalkdirectlytothedatabase.Evenifitcould,forsecurityreasons,youprobablywouldnotwantitto.Thesameargumentappliestomostotherapplications.YouneedtheWebmiddlelayertoextracttheincomingdatafromtheHTTPstream,talktotheapplication,andembedtheresultsinsideadocument.4.Sendtheexplicitdata(i.e.,thedocument)totheclient.Thisdocumentcanbesentinavarietyofformats,includingtext(HTMLorXML),binary(GIFimages),orevenacompressedformatlikegzipthatislayeredontopofsomeotherunderlyingformat.But,HTMLisbyfarthemostcommonformat,soanimportant1servlet/JSPtaskistowraptheresultsinsideofHTML.5.SendtheimplicitHTTPresponsedata.ItshowsasinglearrowgoingfromtheWebmiddlelayer(theservletorJSPpage)totheclient.But,therearereallytwovarietiesofdatasent:thedocumentitselfandthebehind-the-scenesHTTPinformation.Again,bothvarietiesarecriticaltoeffectivedevelopment.SendingHTTPresponsedatainvolvestellingthebrowserorotherclientwhattypeofdocumentisbeingreturned(e.g.,HTML),settingcookiesandcachingparameters,andothersuchtasks.ThesetasksarediscussedinChapters6and7.1.2WhyBuildWebPagesDynamically?AfterMartywrotethefirsteditionofCoreServletsandJavaServerPages,variousofhisnon-software-savvyfriendsandrelationswouldaskhimwhathisbookwasabout.Martywouldlaunchintoalong,technicaldiscussionofJava,object-orientedprogramming,andHTTP,onlytoseetheireyesimmediatelyglazeover.Finally,inexasperation,theywouldask,“Oh,soyourbookisabouthowtomakeWebpages,right?”“Well,no,”theanswerwouldbe,“TheyareabouthowtomakeprogramsthatmakeWebpages.”“Huh?Whywaituntiltheclientrequeststhepageandthenhaveaprogrambuildtheresult?WhynotjustbuildtheWebpageaheadoftime?”Yes,manyclientrequestscanbesatisfiedbyprebuiltdocuments,andtheserverwouldhandletheserequestswithoutinvokingservlets.Inmanycases,however,astaticresultisnotsufficient,andapageneedstobegeneratedforeachrequest.ThereareanumberofreasonswhyWebpagesneedtobebuilton-the-fly:TheWebpageisbasedondatasentbytheclient.Forinstance,theresultspagefromsearchenginesandorderconfirmationpagesatonlinestoresarespecifictoparticularuserrequests.Youdontknowwhattodisplayuntilyoureadthedatathattheusersubmits.Justrememberthattheusersubmitstwokindsofdata:explicit(i.e.,HTMLformdata)andimplicit(i.e.,HTTPrequestheaders).Eitherkindofinputcanbe2usedtobuildtheoutputpage.Inparticular,itisquitecommontobuildauser-specificpagebasedonacookievalue.TheWebpageisderivedfromdatathatchangesfrequently.Ifthepagechangesforeveryrequest,thenyoucertainlyneedtobuildtheresponseatrequesttime.Ifitchangesonlyperiodically,however,youcoulddoittwoways:youcouldperiodicallybuildanewWebpageontheserver(independentlyofclientrequests),oryoucouldwaitandonlybuildthepagewhentheuserrequestsit.Therightapproachdependsonthesituation,butsometimesitismoreconvenienttodothelatter:waitfortheuserrequest.Forexample,aweatherreportornewsheadlinessitemightbuildthepagesdynamically,perhapsreturningapreviouslybuiltpageifthatpageisstilluptodate.TheWebpageusesinformationfromcorporatedatabasesorotherserver-sidesources.Iftheinformationisinadatabase,youneedserver-sideprocessingeveniftheclientisusingdynamicWebcontentsuchasanapplet.Imagineusinganappletbyitselfforasearchenginesite:“Downloading50terabyteapplet,pleasewait!”Obviously,thatissilly;youneedtotalktothedatabase.GoingfromtheclienttotheWebtiertothedatabase(athree-tierapproach)insteadoffromanappletdirectlytoadatabase(atwo-tierapproach)providesincreasedflexibilityandsecuritywithlittleornoperformancepenalty.Afterall,thedatabasecallisusuallytherate-limitingstep,sogoingthroughtheWebserverdoesnotslowthingsdown.Infact,athree-tierapproachisoftenfasterbecausethemiddletiercanperformcachingandconnectionpooling.Inprinciple,servletsarenotrestrictedtoWeborapplicationserversthathandleHTTPrequestsbutcanbeusedforothertypesofserversaswell.Forexample,servletscouldbeembeddedinFTPormailserverstoextendtheirfunctionality.And,aservletAPIforSIP(SessionInitiationProtocol)serverswasrecentlystandardized(see/en/jsr/detail?id=116).Inpractice,however,thisuseofservletshasnotcaughton,andwellonlybediscussingHTTPservlets.Chap2SERVERSETUPANDCONFIGURATION2.1DownloadandInstalltheJavaSoftwareDevelopmentKit(SDK)YouprobablyhavealreadyinstalledtheJavaPlatform,butifnot,doingsoshouldbeyour3firststep.CurrentversionsoftheservletandJSPAPIsrequiretheJava2Platform(StandardEditionJ2SEorEnterpriseEditionJ2EE).IfyouarentusingJ2EEfeatureslikeEnterpriseJavaBeans(EJB)orJavaMessagingService(JMS),werecommendthatyouusethestandardedition.YourserverwillsupplytheclassesneededtoaddservletandJSPsupporttoJava2StandardEdition.ButwhatJavaversiondoyouneed?Well,itdependsonwhatservlet/JSPAPIyouareusing,andwhetheryouareusingafullJ2EE-compliantapplicationserver(e.g.,WebSphere,WebLogic,orJBoss)orastandaloneservlet/JSPcontainer(e.g.,Tomcat,JRun,orResin).Ifyouarestartingfromscratch,werecommendthatyouusethelatestJavaversion(1.4);doingsowillgiveyouthebestperformanceandguaranteethatyouarecompatiblewithfuturereleases.But,ifyouwanttoknowtheminimumsupportedversion,hereisaquicksummary.Servlets2.3andJSP1.2(standaloneservers).Java1.2orlater.J2EE1.3(whichincludesservlets2.3andJSP1.2).Java1.3orlater.Servlets2.4andJSP2.0(standaloneservers).Java1.3orlater.J2EE1.4(whichincludesservlets2.4andJSP2.0).Java1.4orlater.WeuseJava1.4inourexamples.ForSolaris,Windows,andLinux,obtainJava1.4at/j2se/1.4/and1.3at/j2se/1.3/.BesuretodownloadtheSDK(SoftwareDevelopmentKit),notjusttheJRE(JavaRuntimeEnvironment)theJREisintendedonlyforexecutingalreadycompiledJavaclassfilesandlacksacompiler.Forotherplatforms,checkfirstwhetheraJava2implementationcomespreinstalledasitdoeswithMacOSX.Ifnot,seeSunslistofthird-partyJavaimplementationsat/cgi-bin/java-ports.cgi.YourJavaimplementationshouldcomewithcompleteconfigurationinstructions,butthekeypointistosetthePATH(notCLASSPATH!)environmentvariabletorefertothedirectorythatcontainsjavaandjavac,typicallyjava_install_dir/bin.Forexample,ifyouarerunningWindowsandinstalledtheSDKinC:j2sdk1.4.1_01,youmightputthefollowinglineinyourC:autoexec.batfile.Rememberthattheautoexec.batfileisexecutedonlywhenthesystemisbooted.setPATH=C:j2sdk1.4.1_01bin;%PATH%4Ifyouwanttodownloadanalreadyconfiguredautoexec.batfilethatcontainsthePATHsettingandtheothersettingsdiscussedinthischapter,goto/,gotothesourcecodearchive,andselectChapter2.OnWindowsNT/2000/XP,youcouldalsoright-clickonMyComputer,selectProperties,thenAdvanced,thenEnvironmentVariables.Then,youwouldupdatethePATHvalueandpresstheOKbutton.OnUnix(Solaris,Linux,etc.),iftheSDKisinstalledin/usr/j2sdk1.4.1_01andyouusetheCshell,youwouldputthefollowingintoyour.cshrcfile.setenvPATH/usr/j2sdk1.4.1_01/bin:$PATHAfterrebooting(Windows;notnecessaryifyousetthevariablesinteractively)orloggingoutandbackin(Unix),verifythattheJavasetupiscorrectbyopeningaDOSwindow(Windows)orshell(Unix)andtypingjava-versionandjavac-help.Youshouldseearealresultbothtimes,notanerrormessageaboutanunknowncommand.Alternatively,ifyouuseanIntegratedDevelopmentEnvironment(IDE)likeBorlandJBuilder,Eclipse,IntelliJIDEA,orSunONEStudio,compileandrunasimpleprogramtoconfirmthattheIDEknowswhereyouinstalledJava.2.2DownloadaServerforYourDesktopYoursecondstepistodownloadaserver(oftencalleda“servletcontainer”or“servletengine”)thatimplementstheServlet2.3Specification(JSP1.2)ortheServlet2.4Specification(JSP2.0)foruseonyourdesktop.Infact,wetypicallykeepthreeservers(ApacheTomcat,MacromediaJRun,andCauchoResin)installedonourdesktopsandtestapplicationsonalltheservers,tokeepusawareofcross-platformdeploymentissuesandtopreventusfromaccidentallyusingnonportablefeatures.Wellgivedetailsoneachoftheseserversthroughoutthebook.Regardlessoftheserverthatyouuseforfinaldeployment,youwillwantatleastoneserveronyourdesktopfordevelopment.Evenifthedeploymentserverisintheofficenexttoyouconnectedbyalightning-fastnetworkconnection,youstilldontwanttouseitforyourdevelopment.Evenatestserveronyourintranetthatisinaccessibletocustomersismuchlessconvenientfordevelopmentpurposesthanaserverrightonyourdesktop.Runningadevelopmentserveronyourdesktopsimplifiesdevelopmentinanumberofways,ascomparedtodeployingtoa5remoteservereachandeverytimeyouwanttotestsomething.Hereiswhy:Itisfastertotest.Withaserveronyourdesktop,thereisnoneedtouseFTPoranotheruploadprogram.Theharderitisforyoutotestchanges,thelessfrequentlyyouwilltest.Infrequenttestingwillleterrorspersistthatwillslowyoudowninthelongrun.Itiseasiertodebug.Whenrunningonyourdesktop,manyserversdisplaythestandardoutputinanormalwindow.Thisisincontrasttodeploymentserversonwhichthestandardoutputisalmostalwayseitherhiddenoronlyavailableinalogfileafterexecutioniscompleted.So,withadesktopserver,plainoldSystem.out.printlnstatementsbecomeusefultracinganddebuggingutilities.Itissimpletorestart.Duringdevelopment,youwillfindthatyoufrequentlyneedtorestarttheserverorreloadyourWebapplication.Forexample,theservertypicallyreadstheweb.xmlfile(seeSection2.11,“WebApplications:APreview”)onlywhentheserverstartsoraserver-specificcommandisgiventoreloadaWebapplication.So,younormallyhavetorestarttheserverorreloadtheWebapplicationeachtimeyoumodifyweb.xml.Evenwhenservershaveaninteractivemethodofreloadingweb.xml,taskssuchasclearingsessiondata,resettingtheServletContext,orreplacingmodifiedclassfilesusedindirectlybyservletsorJSPpages(e.g.,beansorutilityclasses)maystillnecessitatethattheserverberestarted.Someolderserversalsoneedtoberestartedbecausetheyimplementservletreloadingunreliably.(Normally,serversinstantiatetheclassthatcorrespondstoaservletonlyonceandkeeptheinstanceinmemorybetweenrequests.Withservletreloading,aserverautomaticallyreplacesservletsthatareinmemorybutwhoseclassfileshavechangedonthedisk.)Besides,somedeploymentserversrecommendcompletelydisablingservletreloadingtoincreaseperformance.So,itismuchmoreproductivetodevelopinanenvironmentinwhichyoucanrestarttheserverorreloadtheWebapplicationwithaclickofthemousewithoutaskingfor6permissionfromotherdeveloperswhomightbeusingtheserver.Itismorereliabletobenchmark.Althoughitisdifficulttocollectaccuratetimingresultsforshort-runningprogramseveninthebestofcircumstances,runningbenchmarksonmultiusersystemsthathaveheavyandvaryingsystemloadsisnotoriouslyunreliable.Itisunderyourcontrol.Asadeveloper,youmaynotbetheadministratorofthesystemonwhichthetestordeploymentserverruns.Youmighthavetoasksomesystemadministratoreverytimeyouwanttheserverrestarted.Or,theremotesystemmaybedownforasystemupgradeatthemostcriticaljunctureofyourdevelopmentcycle.Notfun.Itiseasytoinstall.Downloadingandconfiguringaservertakesnomorethananhour.Byusingaserveronyourdesktopinsteadofaremoteone,youllprobablysaveyourselfthatmuchtimetheveryfirstdayyoustartdeveloping.Ifyoucanrunthesameserveronyourdesktopthatyouusefordeployment,allthebetter.So,ifyouaredeployingonBEAWebLogic,IBMWebSphere,Oracle9iAS,etc.,andyourlicensepermitsyoutoalsoruntheserveronyourdesktop,byallmeansdoso.ButoneofthebeautiesofservletsandJSPisthatyoudonthaveto;youcandevelopwithoneserveranddeploywithanother.Followingaresomeofthemostpopularfreeoptionsfordesktopdevelopmentservers.Inallcases,thefreeversionrunsasastandaloneWebserver.Inmostcases,youhavetopayforthedeploymentversionthatcanbeintegratedwitharegularWebserverlikeMicrosoftIIS,iPlanet/SunONEServer,Zeus,ortheApacheWebServer.However,theperformancedifferencebetweenusingoneoftheserversasaservletandJSPenginewithinaregularWebserverandusingitasacompletestandaloneWebserverisnotsignificantenoughtomatterduringdevelopment.See/products/servlet/industry.htmlforamorecompletelistofserversandserverpluginsthatsupportservletsandJSP.ApacheTomcat.Tomcat5ApacheTomcat.Tomcat5istheofficialreferenceimplementationoftheservlet2.4andJSP2.0specifications.Tomcat4istheofficialreferenceimplementationforservlets2.3(JSP71.2).BothversionscanbeusedasstandaloneserversduringdevelopmentorcanbepluggedintoastandardWebserverforuseduringdeployment.LikeallApacheproducts,Tomcatisentirelyfreeandhascompletesourcecodeavailable.Ofalltheservers,italsotendstobetheonethatismostcompliantwiththelatestservletandJSPspecifications.However,thecommercialserverstendtobebetterdocumented,easiertoconfigure,andfaster.TodownloadTomcat,startat/tomcat/,gotothebinariesdownloadsection,andchoosethelatestreleasebuildofTomcat.MacromediaJRun.JRunisaservletandJSPenginethatcanbeusedinstandalonemodefordevelopmentorpluggedintomostcommoncommercialWebserversfordeployment.Itisfreefordevelopmentpurposes,butyoumustpurchasealicensebeforedeployingwithit.ItisapopularchoiceamongdeveloperslookingforeasieradministrationthanTomcat.Fordetails,see/software/jrun/.CauchosResin.ResinisafastservletandJSPenginewithextensiveXMLsupport.AlongwithTomcatandJRun,itisoneofthethreemostpopularserversusedbycommercialWebhostingcompaniesthatprovideservletandJSPsupport.Itisfreefordevelopmentandnoncommercialdeploymentpurposes.Fordetails,see/products/resin/.NewAtlantasServletExec.ServletExecisanotherpopularservletandJSPenginethatcanbeusedinstandalonemodefordevelopmentor,fordeployment,pluggedintotheMicrosoftIIS,Apache,andSunONEservers.Youcandownloadanduseitforfree,butsomeofthehighperformancecapabilitiesandadministrationutilitiesaredisableduntilyoupurchasealicense.TheServletExecDebuggeristheconfigurationyouwoulduseasastandalonedesktopdevelopmentserver.Fordetails,see/products/servletexec/.Jetty.Jettyisanopen-sourceserverthatsupportsservletsandJSPtechnologyandisfreeforbothdevelopmentanddeployment.Itisoftenusedasacompletestandaloneserver(ratherthanintegratedinsideanon-JavaWebserver),evenfordeployment.Fordetails,see8/jetty/.Chap3SERVLETBASIC3.1BasicServletStructureListing3.1outlinesabasicservletthathandlesGETrequests.GETrequests,forthoseunfamiliarwithHTTP,aretheusualtypeofbrowserrequestsforWebpages.AbrowsergeneratesthisrequestwhentheuserentersaURLontheaddressline,followsalinkfromaWebpage,orsubmitsanHTMLformthateitherdoesnotspecifyaMETHODorspecifiesMETHOD=GET.ServletscanalsoeasilyhandlePOSTrequests,whicharegeneratedwhensomeonesubmitsanHTMLformthatspecifiesMETHOD=POST.FordetailsontheuseofHTMLformsandthedistinctionsbetweenGETandPOST,seeChapter19(CreatingandProcessingHTMLForms).SincedoGetanddoPostthrowtwoexceptions(ServletExceptionandIOException),youarerequiredtoincludetheminthemethoddeclaration.Finally,youmustimportclassesinjava.io(forPrintWriter,etc.),javax.servlet(forHttpServlet,etc.),andjavax.servlet.http(forHttpServletRequestandHttpServletResponse).However,thereisnoneedtomemorizethemethodsignatureandimportstatements.Instead,simplydownloadtheprecedingtemplatefromthesourcecodearchiveat/anduseitasastartingpointforyourservlets.3.2AServletThatGeneratesPlainTextListing3.2showsasimpleservletthatoutputsplaintext,withtheoutputshowninFigure32.Beforewemoveon,itisworthspendingsometimereviewingtheprocessofinstalling,compiling,andrunningthissimpleservlet.SeeChapter2(ServerSetupandConfiguration)foramuchmoredetaileddescriptionoftheprocess.First,besurethatyouvealreadyverifiedthebasics:ThatyourserverissetupproperlyasdescribedinSection2.3(ConfiguretheServer).ThatyourdevelopmentCLASSPATHreferstothenecessarythreeentries(theservletJARfile,yourtop-leveldevelopmentdirectory,and“.”)asdescribedinSection2.7(SetUpYourDevelopmentEnvironment).ThatallofthetestcasesofSection2.8(TestYourSetup)executesuccessfully.Second,type“javacHelloWorld.java”ortellyourdevelopmentenvironmenttocompiletheservlet(e.g.,9byclickingBuildinyourIDEorselectingCompilefromtheemacsJDEmenu).ThisstepwillcompileyourservlettocreateHelloWorld.class.Third,moveHelloWorld.classtothedirectorythatyourserverusestostoreservletsthatareinthedefaultWebapplication.Theexactlocationvariesfromservertoserver,butistypicallyoftheforminstall_dir/./WEB-INF/classes(seeSection2.10fordetails).ForTomcatyouuseinstall_dir/webapps/ROOT/WEB-INF/classes,install_dir/servers/default/default-ear/default-war/WEB-INF/classes,andforResinyouuseinstall_dir/doc/WEB-INF/classes.Alternatively,youcanuseoneofthetechniquesofSection2.9(EstablishaSimplifiedDeploymentMethod)toautomaticallyplacetheclassfilesintheappropriatelocation.10Servlet与JSP核心编程第1章servlet和JSP技术概述1.1servlet的功用Servlet是运行在Web服务器或应用服务器上的Java程序,它是一个中间层,负责连接来自Web浏览器或其他HTTP客户程序的请求和HTTP服务器上的数据库或应用程序。(1)读取客户发送的显示数据。最终用户一般在网页的HTML表单中输入这些数据,然而,数据还有可能来自于applet或定制的HTTP客户程序。Servlet如何读取这些数据在第4章中论述。(2)读取由浏览器发送的隐式请求数据中间层的构架显示了一条从客户到Web服务器(servlet和JSP所在的层)的单箭头,但是实际上从客户端传送到Web服务器的数据有两种,它们分别为用户在表单中输入显示数据,以及后台的HTTP信息。两种数据都很重要。HTTP信息包括cookie、浏览器所能识别的媒体类型和压缩模式等;这部分内容在第5章详细论述。(3)生成结果这个过程可能需要访问数据库、执行RMI或EJB调用、调用Web服务,或者直接计算得出对应的响应。实际的数据可能存储在关系型数据库中。该数据可能不理解HTTP,或者不能返回HTML形式的结果,所以Web浏览器不能直接与数据库进行会话。即使它能过做到这一点,为了安全上的考虑,我们也不希望让它这样做。对于大多数其他应用程序,也存在类似的问题。因此,我们需要Web中间层从HTTP流中提取输入数据,与应用程序会话,并将结果嵌入到文档中。(4)向客户发送显示数据这个文档可以用各种格式发送,包括文本(HTML或XML),二进制(GIF图),甚至可以是建立在其他底层格式之上的压缩格式,如gzip。但是,到目前为止,HTML是最常用的格式,故而servlet和JSP的重要任务之一就是将结果包装到HTML中。(5)发送一个隐式的HTTP响应数

温馨提示

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

评论

0/150

提交评论