




已阅读5页,还剩7页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
文献翻译-1-Javaservlet本章介绍Java中的服务器端程序设计。到目前为止,我们已经介绍了单机的应用程序,很多读者可能已经熟悉了用于客户端程序设计的applet。Java作为程序设计平台的其中一个优势在于服务器端程序设计,它取代CGI脚本,与浏览器和用户交互,提供定制功能。在这儿,Java由于使用在应用程序中,所以与传统的applet相比,它访问本地资源的活动受到的限制较少,而且安全约束也更少。提示:Javaservlet是Java2企业版(J2EE)的补充技术的一部分。这些技术适合于开发大、中型应用程序,它们包括EnterpriseJavaBean(EJB)、JavaServerPage(JSP)等。它们完全有资格值得用整本书来论述,超出了这样一本介绍网络编程的书的讨论范围。1、servlet概述虽然Javaapplet的动态、交互特性使得它们对Web管理者很有吸引力,但是applet受到安全策略的严格限制。这些目的在于保护用户的安全策略,让那些想创建在浏览器中运行的成熟应用程序的开发者无法施展拳脚。加载applet需要很长时间,而且目前还缺乏跨越所有浏览器的广泛的Java2支持,当综合考虑这些因素时,服务器端内容通常要胜过Javaapplet中的内容。以前,为了创建服务器端应用程序,开发者至少需要掌握一种脚本语言,如Perl或用于动态服务器页面的VBScript。这样的做法,通常把开发者束缚在某种特殊的Web服务器框架或操作系统之上。这可能使程序员灰心丧气,因为他们再也不能使用熟悉的JavaAPI,再也不能自由开发可移植的应用程序。幸运的是,Sun公司已预见有对服务器端Java的需要,因此servlet应运而生。虽然目前Sun只提供基本的、基于HTTP的servlet实现,但是,可以结合其他请求响应协议使用servlet。Javaservlets是执行过程与CGI脚本相似,但不独立处理每个请求(独立处理消耗了CPU时间和内存资源)的服务器端应用程序。servlet是多线程应用,因此可以在servlet实例之间共享资源。通过在脚本解释器上使用已编译的语言而产生的性能提高,也使得servlet对开发者来说,是一个不错的选择。当然,对servlet开发者而言,最明显的好处是,servlet是用Java写的。它具有Java语言的所有特性,如面向对象、可移植性、包括联网支持在内的大量API、以及易用性,而且还消除了applet易受到的安全约束。2、使用servletservlet依赖于javax.servlet包和javax.servlet.http包中定义的类。这些包是JavaAPI的标准扩展,与JavaServlet开发包以及很多servlet兼容的Web服务器一起交付。servlet的起点是servlet接口。这个接口为servlet提供基本的构造方法,例如初始化、服务、以及撤消的方法(destructionmethod)。它还提供访问servlet环境和配置-2-的方法,如本章后面所示。在默认情况下,实现这个接口的servlet使用共享线程模型,这个模型极大地提高了servlet处理大量请求的性能。还可以使用10.6节讨论的另一个单线程模型。如我们将看到的那样,这是个有缺陷的模型,在通常情况下不应该使用。在共享线程模型中,servlet引擎为每个servlet创建一个实例,该实例被所有请求共享。然后,引擎为每个到达的请求各自创建一个线程,然后把servlet的service方法传递给各个线程。这意味着不能假定类变量和实例变量是线程安全变量。当然,常量是非可变的,不用考虑它们。使用方法变量,并在方法调用中传递这些变量无需太多工作,只需避免在方法调用中传递类和实例变量。下面的范例显示怎样正确使用变量badVaribale和goodVaribale。publicintvadVaribale;publicvoiddoGet(HttpServletRequesreq,HttpServletResponseres)ThrowsIOExceptionpublicintgoodVaribale;为了实际创建servlet,Sun提供了GenericServlet类和HTTPServlet类。这些类的功能和applet很相似,因为可以扩展它们,以提供额外的功能。GenericServlet类通过简单实现init()方法和destroy()方法,给出了一般性的协议无关的起始点,因此开发者只需扩展服务。然而,如果要编写的是用于Web的HTTPservlet,那么应用扩展HTTPServlet类,它由GenericServlet类扩展而来,可以以它为基础创建Webservlet。除非已做了功能上的变更,否则HttpServlet类的service()方法将检查浏览器发出的HTTP请求类型,并把它传递给特定的处理器函数。尽管可以编写自定义的service()方法,但是在多数情况下,使用默认的service方法会更简单。对于每一种主要的Http请求类型,都有一个相应的、开发者可以覆盖的处理器函数。表10_1列出了HTTP请求和servlet方法之间的映射。表10-1HTTP请求类型和servlet方法之间的映射HTTP请求Servlet处理函数GETdoGet(HttpServletRequest,HttpServletResponse)POSTdoPost(HttpServletRequest,HttpServletResponse)PUTdoPut(HttpServletRequest,HttpServletResponse)-3-DELETEdoDelete(HttpServletRequest,HttpServletResponse)TRACEdoTrace(HttpServletRequest,HttpServletResponse)OPTIONSdoOptions(HttpServletRequest,HttpServletResponse)开发者可以自由覆盖这些处理器函数中的一个、几个或者全部。然而,如果处理器函数未被覆盖,那么它将返回HTTP_BAD_REQUEST错误响应。例如,假设表单servlet只支持Post请求。下面的例子演示了这样一个事务处理可能会是什么样子:Browser:GET/servlet/form_handler?email=HTTP/1.0Serrver:400Badrequestfrombrowser提示由于所有处理器函数都带同样的参数(HttpServletRequest类和HttpServletResponse类的实例),所以为把控制传递给GET方法或POST方法编写处理器不难。这意味着如果你偶然在HTML表单中指定了错误的HTTP方法,那么servlet可以得体地处理。例如,为了把GET请求传送给POST方法,你可以添加下面的代码:publicvoiddoGet(HttpServletRequesreq,HttpServletResponseres)ThrowsIOExceptiondoPost(req,res);一旦调用servlet处理器函数,那么它就可以对请求及其参数做出响应,进行一些处理,然后输出响应。然而,开发者应该注意,每个servlet都可以同时服务多个请求,所以会有常见的线程安全问题。最后,当Web服务器因为指定的时间到而关闭或终止servlet时,将调用destroy()方法。这是servlet关闭打开的文件、删除临时或不必要的数据文件、向磁盘提交所做的修改、或者关闭打开的网络/数据库连接的最后机会。与applet一样,servlet从创建到撤消也是有有限的生命周期的。最开始是调用init()方法,接着是一个或多个service()请求,最后调用destroy()方法。2.1、GET和POSTGET和POSTHTTP请求类型被用来检查来自Web服务器的数据,它们两个都能够把参数编码成请求。两者之间的惟一主要差别是,GET的参数被限定为255个字符,而POST则不受此限制。在GET请求中,URL中的问号表示URL的余下部分包含着已编码的参数。下面是一个已对参数进行了编码的简单GET请求的例子:GER/servlet/Query?name=tom&age=28HTTP/1.0而POST请求不修改被请求的URL。相反,POST请求后面跟着被发送到服务器-4-端脚本或servlet的实际参数。下面是一个简单的POST请求的例子,它的功能与前面的GET请求相同:PSOT/servelt/QueryHTTP/1.0name=tomage=28据JavaServletAPI看来,这两种请求被视作完全不同。然而,这些差异对开发者来说是明显的,因为API提供的通用方法抽象了它们之间的差异。在很多情况下,编写一个处理器来处理GET请求和POST请求,比把GET处理器和PSOT处理器分开要容易。如果你希望你的servlet更易于管理,那么你可以把GET请求和PSOT请求都提交到一个处理器中,如下面的范例所示:publicvoiddoGet(HttpServletRequesreq,HttpServletResponseres)ThrowsIOExceptiondoPost(req,res);publicvoiddoPost(HttpServletRequesreq,HttpServletResponseres)ThrowsIOException/Implementationgoeshere2.2、PUT和DELETEPUT和DELETE最初被用来向从Web服务器的存储空间中添加/删除文件。例如,你可以用PUT发送新文件,而用DELETE删除文件。当然,在多数应用程序中都限制使用它们想想,某人改写你的页面、上传一个伪装servlet或删除你的Web站点,这将是多么恐怖的事情!尽管如此,但可能还是有读者想把这些方法用做其他用途,或者为他们的Web站点创建受控的上传系统。2.3、TRACE依据HTTP/1.1规范中与TRACE方法结果有关的部分所说,“用TRACE方法来调用请求信息的远程应用层回送。”它被用来诊断测试servlet请求,不必为了提供实现而覆盖这个方法。不过,如果因为调试的原因而有必要覆盖,则Sun也允许开发者这样做。2.4、OPTIONSHTTP中的OPTIONS请求类型通常被用来探测服务器或者一个servlet,以了解目前哪些HTTP请求类型有效。例如,当你扩展HTTPServlet类并只实现了doGet方法时,你将从OPTION请求中接收到下面的输出:-5-Allow:GET,HEAD,TRACE,OPTIONS除非计划添加HTTP/1.1以外的其他方法,否则没必要实现这个方法。原文:Chapter10.JavaServletsThischapterprovidesanintroductiontoserver-sideprogramminginJava.Thusfar,wevedealtwithstand-aloneapplications,andmanyreadersmayalreadybefamiliarwithappletsforclient-sideprogramming.OneofJavasstrengthsasaprogrammingplatformliesinserver-sideprogramming,asasubstituteforCGIscriptsthatinteractwithbrowsersanduserstoprovideacustomexperience.Here,asinapplications,Javasoftwareislessrestrictedinitsactivities,havingaccesstolocalresourcesandfewersecurityrestrictionsthanthetraditionalapplet.NOTE:JavaservletsformpartofabroadcomplementoftechnologiesknownastheJava2EnterpriseEdition(J2EE).Thesetechnologiesaresuitedtomedium-tolarge-scaleapplicationdevelopment,andincludetopicssuchasEnterpriseJavaBeans(EJBs),JavaServerPages(JSPs),andmuchmore.Suchtechnologiesmeritbook-lengthcoverageintheirownright,andarebeyondthescopeofanintroductorynetworkprogrammingbooksuchasthis.10.1OverviewWhilethedynamicandinteractivenatureofJavaappletsmakesthemanattractivechoiceforWebmasters,appletsareseverelylimitedbysecuritypolicies.Suchpolicies,aimedatprotectingusers,canberestrictivefordeveloperswhowanttocreatefull-fledgedapplicationsthatruninsideabrowser.WhencombinedwithslowloadingtimesandlackofuniversalJava2supportacrossallbrowsers,theadvantagesofserver-sidecontentoftenoutweighthoseofJavaapplets.Previously,developerswouldneedtomasteroneormorescriptinglanguages,suchasPerlorVBScriptforActiveServerPages,tocreateserver-sideapplications.SuchapproachesoftentieddevelopersintoaparticularWebserverframeworkoroperatingsystem.Thiswasfrustratingfordevelopers,astheynolongerhadaccesstotherichJavaAPItheywerefamiliarwith,northefreedomofportableapplicationdevelopment.Fortunately,SunMicrosystemsperceivedtheneedforserver-sideJava,andservletswereborn.WhileSuncurrentlyprovidesonlyabaselineandHTTPimplementationofservlets,itispossibletouseservletswithotherrequest-responseprotocols.Javaservletsareserver-sideapplicationsthatexecutesimilartoCGIscripts,but-6-withoutaseparateprocessforeachrequest(whichconsumesbothCPUandmemoryresources).Servletsaremulti-threaded,andthuscanshareresourcesacrossservletinstances.Theperformanceincreasethatcomeswithusingacompiledlanguageoverascriptinginterpreteralsomakesservletsagoodchoicefordevelopers.Ofcourse,themostobviousbenefitforservletdevelopersisthatservletsarewritteninJava.AllofthefeaturesoftheJavalanguage,suchasobjectorientation,portability,theextensiveAPIincludingnetworkingsupport,andeaseofuse,areprovided,withoutthesecurityrestrictionsthatappletsaresubjectto.10.3UsingServletsServletsrelyonclassesdefinedinthejavax.servletandjavax.servlet.httppackages.ThesepackagesareastandardextensiontotheJavaAPI,andshipwiththeJavaServletDevelopmentKit(JSDK)aswellasmanyservlet-compatibleWebservers.Thestartingpointforaservletistheservletinterface.Thisinterfaceprovidesthebasicstructuremethodsforservlets,suchastheinitializing,service,anddestructionmethods.Italsoprovidesstructuremethodsforaccessingtheservletscontextandconfiguration,asshownlaterinthischapter.Bydefault,servletsthatimplementthisinterfaceuseasharedthreadingmodelthatdrasticallyimprovestheperformanceofservletstohandlelargenumbersofrequests.Analternativesingle-threadingmodel,discussedinSection10.6,isalsoavailable.Asweshallsee,thiscanbeaflawedmodelandshouldnotbeusedundernormalcircumstances.Inthesharedthreadingmodel,theservletenginecreatesasingleinstanceofeachservletthatissharedbyallrequests.Theenginethencreatesathreadforeachrequestthatcomesinandpassestheservletsservicemethodtothethreads.Whatthismeansisthatclassandinstancevariablescannotbepresumedtobethread-safevariables.Constants,ofcourse,areimmutableandarenotofanyconcern.Usingmethodvariablesandpassingthosevariablesaroundinmethodcallsdoesnotrequiremuchmoreworkandonlynecessitatesthatclassandinstancevariablesbeavoided.TheexamplebelowshowstheproperuseofbadVariableandgoodVariable.publicintbadVariable;publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)throwsIOExceptionpublicintgoodVariable;Fortheactualcreationofaservlet,SunprovidestheGenericServletandHTTPServletclasses.Theseclassesfunctionverymuchlikeapplets,inthattheycanbe-7-extendedtoprovideadditionalfunctionality.TheGenericServletprovidesagenericprotocol-independentstartingpointwithsimpleimplementationsofinit()anddestroy(),sothatthedeveloperneedsonlytoextendservice.However,ifthegoalistowriteanHTTPservletthatisusedfortheWeb,theHTTPServletclassshouldbeextended;itextendsfromGenericServletandprovidesthestartingpointforWebservlets.Unlessthefunctionalityischanged,theservice()methodofHttpServletwillcheckthetypeofHTTPrequestsentbythebrowserandpassitofftospecialhandlerfunctions.Whileitispossibletowriteacustomservice()method,inmostcasesitiseasiertousethedefaultservicemethod.ForeachofthemajorHTTPrequesttypes,thereisacorrespondinghandlerfunctionthatcanbeoverriddenbydevelopers.Table10-1showsthemappingbetweenHTTPrequestsandservletmethods.Table10-1.MappingofHTTPRequestTypestoServletMethodsHTTPRequestServletHandlerFunctionGETdoGet(HttpServletRequest,HttpServletResponse)POSTdoPost(HttpServletRequest,HttpServletResponse)PUTdoPut(HttpServletRequest,HttpServletResponse)DELETEdoDelete(HttpServletRequest,HttpServletResponse)TRACEdoTrace(HttpServletRequest,HttpServletResponse)OPTIONSdoOptions(HttpServletRequest,HttpServletResponse)Developersarefreetooverrideone,several,orallofthesehandlerfunctions.However,ifahandlerfunctionisnotoverridden,itwillreturnanHTTP_BAD_REQUESTerrorresponse.Forexample,supposeaformservletsupportedonlythePOSTrequest.Hereisasampleofwhatsuchatransactionmightlooklike.Browser:GET/servlet/form_handler?email=HTTP/1.0Server:400BadrequestfrombrowserNOTE:Sinceallofthehandlerfunctionstakethesameparameters(aninstanceofHttpServletRequestandHttpServletReponse),itiseasytowriteahandlerforeitherGETorPOSTthatpassescontrolofftotheother.ThismeansthatifyouaccidentallyspecifythewrongHTTPmethodinyourHTMLforms,theservletwillhandleitgracefully.Forexample,topassGETrequestsofftoaPOSTmethod,youcouldaddthefollowinglines:publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)throwsIOException-8-doPost(req,res);Onceaservlethandlerfunctioniscalled,itcanrespondtotherequestanditsparameters,performsomeprocessing,andthenoutputaresponse.However,developersshouldbemindfulofthefactthateachservletiscapableofservicingmultiplerequestssimultaneously,sonormalthreadsafetyissuesapply.Finally,whentheWebservershutsdownorterminatesaservletduetoinactivityafteraspecifiedperiodoftime,thedestroy()methodwillbeinvoked.Thisistheservletslastopportunitytocloseopenfiles,removetemporaryorunnecessarydatafiles,commitchangestodisk,orcloseopennetwork/databaseconnections.Aswithapplets,servletshaveadefinitelifecyclefromcreationtodestruction.Firsttheinit()methodiscalled,followedbyoneormoreservice()requests,andfinallyadestroy()callismade.10.3.1GETandPOSTTheGETandPOSTHTTPrequesttypesareusedtoretrievedatafromaWebserver,andbothhavetheabilitytoencodeparametersintotherequest.TheonlymajordifferencebetweenthemisthatGEThasalimitof255charactersforitsparameters,whilePOSThasnolimit.AGETrequestinvolvesusingaquestionmarkintheURLtosignifythattherestoftheURLincludesencodedparameters.AnexampleofasimpleGETrequestthatencodesparametersis:GET/servlet/Query?name=tom&age=28HTTP/1.0APOSTrequest,ontheotherhand,doesnotmodifytheURLthatisrequested.Instead,thePOSTrequestisfollowedbytheactualparametersthataresenttotheserver-sidescriptorservlet.AnexampleofasimplePOSTrequest,whichperformsthesamejobasthepreviousGETrequest,isthefollowing:POST/servlet/QueryHTTP/1.0name=tomage=28AccordingtotheJavaServletAPI,thesetwotypesofrequestsaretreatedcompletelydifferently.However,thesedifferencesaretransparenttothedeveloper,astheAPIprovidesgenericmethodsthatabstractthedifferencesbetweenthem.Inmanycases,itiseasiertowriteasinglehandlerthantodividetheworkbetweenaGETandaPOSThandler.Assumingthatyouwouldlikeyourservlettobeeasilymanageable,youcanreferbothGETandPOSTrequeststoasinglehandler,asshowninthisexample:publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)throwsIOException-9-doGetPost(req,res);publicvoiddoPost(HttpServletRequestreq,HttpServletResponseres)throwsIOExceptiondoGetPost(req,res);publicvoiddoGetPost(HttpServletRequestreq,HttpServletResponseres)throwsIOException/Implementat
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 通风排烟安装工程合同
- 2022学年上海交大附中高一(下)期中政治试题及答案
- 宇宙之谜探索诗歌中的艺术特色与灵感教学教案
- 春季活动策划方案
- 无锡2025高三期末语文作文(9篇)
- 词句积累与运用:古诗词赏析与记忆训练初中英语课教案
- 宇宙探索与科幻文学:初中语文拓展教学教案
- 公交公司联欢会活动方案
- 物质的三种状态及其性质:九年级科学物理教案
- 公众号售卖活动方案
- 北京市顺义区2023-2024学年五年级下学期数学期末试卷(含答案)
- 2025公基题库(附答案解析)
- 2025年宁夏银川灵武市选聘市属国有企业管理人员招聘笔试冲刺题(带答案解析)
- 机关内部制度管理制度
- 2025年高纯硫酸锶项目市场调查研究报告
- 2025年汽车驾照考试科目一考试题库及参考答案
- 广东省广州市天河区2023-2024学年七年级下学期期末考试英语试题(含答案)
- 净水机服务合同协议书
- 古城煤矿压风系统远程监控改造技术协议
- 2025年上海市公务员录用考试《行测》真题及答案解析(B类)
- 村务管理岗面试题及答案
评论
0/150
提交评论