




已阅读5页,还剩12页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
外文文献1.WhatisstrutsStrutsisopensourcesoftwarethathelpsdevelopersbuildwebapplicationsquicklyandeasily.StrutsreliesonstandardtechnologiessuchasJavaBeans,Javaservlets,andJavaServerPages(JSP)thatmostdevelopersalreadyknowhowtouse.Bytakingastandards-based,“fill-in-the-blanks”approachtosoftwaredevelopment,Strutscanalleviatemuchofthetime-consuminggruntworkthatcomeswitheverynewproject.2.WhomakestheStrutssoftwareStrutsishostedbytheApacheSoftwareFoundation(ASF)aspartofitsJakartaproject.BesidesStruts,Jakartahostsseveralsuccessfulopensourceproducts,includingTomcat,Ant,andVelocity.TheinitialStrutscodebasewasdevelopedbetweenMay2000andJune2001whenversion1.0wasreleased.Morethan30developerscontributedtotheStrutsdistribution,andthousandsmorefollowtheStrutsmailinglists.TheStrutscodebaseismanagedbyateamofvolunteer“Committers.”By2002,theStrutsteamincludednineactiveCommitters.TheprimaryarchitectanddeveloperoftheStrutsframeworkisCraigR.McClanahan.CraigisalsotheprimaryarchitectofTomcat4andtheimplementationarchitectoftheJavaWebServicesDeveloperPack.HeisnowSunsspecificationleadforJavaServerFaces(JSR-127)aswellastheWebLayerArchitectfortheJava2EnterpriseEdition(J2EE)platform.StrutsisavailabletothepublicatnochargeundertheApacheSoftwareLicenseASF,License.Therearenoacquisitionorotherrecurringcostsforusingthesoftware.Unlikesomeotheropensourcelicenses,theApacheSoftwareLicenseisbusiness-friendly.YoucanuseStrutstocreateacommercialprojectanddistributetheStrutsbinarywithoutanyredtape,fees,orotherhassles.YoucanalsointegratetheStrutscomponentsintoyourownframeworkjustasiftheywerewrittenin-house.Forcompletedetails,seetheApacheSoftwareL/LICENSE.2.1.1.WhyisStrutsopensourceMostoftheleadingJavautilitiesandframeworksarenowopensourceprojects.ManyofthedevelopersworkingontheseprojectsdosoaspartoftheirregularjobswithcompanieslikeIBM,SunMicrosystems,andApple.Collaboratingopenlyonthistypeofsoftwarebenefitstheentiremarketplace.Today,manyopensourcecomponentsareintegratedintocommercialproducts.Companiesthensellprofessionaldocumentation,guaranteedsupportlevels,andothervaluableaftermarketservicestotheirclients.Whensoftwareisfreelyavailable,itbecomesmucheasierforthemarketplacetosupport.Strutsisaprimeexampleofthis.Althoughstillayoungster,ithasalreadybeenfeaturedindozensofarticlesandseminars,nottomentionbookslikethisone.Manydevelopmentteamsdonotliketousesoftwarethatwasnot“invented”in-house.Opensourcecomponentsprovideallthebenefitsofwritingthesamesoftwarein-housebutdonotlockyouintoaproprietarysolutionthatonlyyourteamunderstands.Opensourceframeworksareawin-winforeveryone.2.1.2.WhyisitcalledStrutsTheframeworkiscalled“Struts”toremindusoftheinvisibleunderpinningsthatholdupourhouses,buildings,bridges,and,indeed,ourselveswhenweareonstilts.ThisisanexcellentdescriptionoftheroleStrutsplaysindevelopingwebapplications.Whenraisingphysicalstructures,constructionengineersusestrutstoprovidesupportforeachfloorofabuilding.Likewise,softwareengineersuseStrutstosupporteachlayerofabusinessapplication.3.WhatareapplicationframeworksAframeworkisareusable,semi-completeapplicationthatcanbespecializedtoproducecustomapplicationsJohnson.Likepeople,softwareapplicationsaremorealikethantheyaredifferent.Theyrunonthesamecomputers,expectinputfromthesamedevices,outputtothesamedisplays,andsavedatatothesameharddisks.Developersworkingonconventionaldesktopapplicationsareaccustomedtotoolkitsanddevelopmentenvironmentsthatleveragethesamenessbetweenapplications.Applicationframeworksbuildonthiscommongroundtoprovidedeveloperswithareusablestructurethatcanserveasthefoundationfortheirownproducts.Aframeworkprovidesdeveloperswithasetofbackbonecomponentsthathavethefollowingcharacteristics:_Theyareknowntoworkwellinotherapplications._Theyarereadytousewiththenextproject._Theycanalsobeusedbyotherteamsintheorganization.Frameworksaretheclassicbuild-versus-buyproposition.Ifyoubuildit,youwillunderstanditwhenyouaredonebuthowlongwillitbebeforeyoucanrollyourown?Ifyoubuyit,youwillhavetoclimbthelearningcurveandhowlongisthatgoingtotake?Thereisnorightanswerhere,butmostobserverswouldagreethatframeworkssuchasStrutsprovideasignificantreturnoninvestmentcomparedtostartingfromscratch,especiallyforlargerprojects.3.1OthertypesofframeworksTheideaofaframeworkappliesnotonlytoapplicationsbuttoapplicationcomponentsaswell.Throughoutthisbook,weintroduceothertypesofframeworksthatyoucanusewithStruts.TheseincludetheLucenesearchengine,theScaffoldtoolkit,theStrutsvalidator,andtheTilestaglibrary.Likeapplicationframeworks,thesetoolsprovidesemi-completeversionsofasubsystemthatcanbespecializedtoprovideacustomcomponent.Someframeworkshavebeenlinkedtoaproprietarydevelopmentenvironment.ThisisnotthecasewithStrutsoranyoftheotherframeworksshowninthisbook.YoucanuseanydevelopmentenvironmentwithStruts:VisualAgeforJava,JBuilder,Eclipse,Emacs,andTextpadareallpopularchoicesamongStrutsdevelopers.IfyoucanuseitwithJava,youcanuseitwithStruts.3.2EnablingtechnologiesApplicationsdevelopedwithStrutsarebasedonanumberofenablingtechnologies.ThesecomponentsarenotspecifictoStrutsandunderlieeveryJavawebapplication.AreasonthatdevelopersuseframeworkslikeStrutsistohidethenastydetailsbehindacronymslikeHTTP,CGI,andJSP.AsaStrutsdeveloper,youdontneedtobeanalphabetsoupguru,butaworkingknowledgeofthesebasetechnologiescanhelpyoudevisecreativesolutionstotrickyproblems.3.2.1HypertextTransferProtocol(HTTP)Whenmediatingtalksbetweennations,diplomatsoftenfollowaformalprotocol.Diplomaticprotocolsaredesignedtoavoidmisunderstandingsandtokeepnegotiationsfrombreakingdown.Inasimilarvein,whencomputersneedtotalk,theyalsofollowaformalprotocol.Theprotocoldefineshowdataistransmittedandhowtodecodeitonceitarrives.WebapplicationsusetheHypertextTransferProtocol(HTTP)tomovedatabetweenthebrowserrunningonyourcomputerandtheapplicationrunningontheserver.ManyserverapplicationscommunicateusingprotocolsotherthanHTTP.Someofthesemaintainanongoingconnectionbetweenthecomputers.Theapplicationserverknowsexactlywhoisconnectedatalltimesandcantellwhenaconnectionisdropped.Becausetheyknowthestateofeachconnectionandtheidentityofeachpersonusingit,theseareknownasstatefulprotocols.Bycontrast,HTTPisknownasastatelessprotocol.AnHTTPserverwillacceptanyrequestfromanyclientandwillalwaysprovidesometypeofresponse,eveniftheresponseisjusttosayno.Withouttheoverheadofnegotiatingandretainingaconnection,statelessprotocolscanhandlealargevolumeofrequests.ThisisonereasonwhytheInternethasbeenabletoscaletomillionsofcomputers.AnotherreasonHTTPhasbecometheuniversalstandardisitssimplicity.AnHTTPrequestlookslikeanordinarytextdocument.ThishasmadeiteasyforapplicationstomakeHTTPrequests.YoucanevensendanHTTPrequestbyhandusingastandardutilitysuchasTelnet.WhentheHTTPresponsecomesback,itisalsoinplaintextthatdeveloperscanread.ThefirstlineintheHTTPrequestcontainsthemethod,followedbythelocationoftherequestedresourceandtheversionofHTTP.ZeroormoreHTTPrequestheadersfollowtheinitialline.TheHTTPheadersprovideadditionalinformationtotheserver.Thiscanincludethebrowsertypeandversion,acceptabledocumenttypes,andthebrowserscookies,justtonameafew.Ofthesevenrequestmethods,GETandPOSTarebyfarthemostpopular.Oncetheserverhasreceivedandservicedtherequest,itwillissueanHTTPresponse.ThefirstlineintheresponseiscalledthestatuslineandcarriestheHTTPprotocolversion,anumericstatus,andabriefdescriptionofthestatus.Followingthestatusline,theserverwillreturnasetofHTTPresponseheadersthatworkinawaysimilartotherequestheaders.Aswementioned,HTTPdoesnotpreservestateinformationbetweenrequests.Theserverlogstherequest,sendstheresponse,andgoesblissfullyontothenextrequest.Whilesimpleandefficient,astatelessprotocolisproblematicfordynamicapplicationsthatneedtokeeptrackoftheirusers.(Ignoranceisnotalwaysbliss.)CookiesandURLrewritingaretwocommonwaystokeeptrackofusersbetweenrequests.Acookieisaspecialpacketofinformationontheuserscomputer.URLrewritingstoresaspecialreferenceinthepageaddressthataJavaservercanusetotrackusers.Neitherapproachisseamless,andusingeithermeansextraworkwhendevelopingawebapplication.Onitsown,astandardHTTPwebserverdoesnottrafficindynamiccontent.Itmainlyusestherequesttolocateafileandthenreturnsthatfileintheresponse.ThefileistypicallyformattedusingHypertextMarkupLanguage(HTML)W3C,HTMLthatthewebbrowsercanformatanddisplay.TheHTMLpageoftenincludeshypertextlinkstootherwebpagesandmaydisplayanynumberofothergoodies,suchasimagesandvideos.Theuserclicksalinktomakeanotherrequest,andtheprocessbeginsanew.Standardwebservershandlestaticcontentandimagesquitewellbutneedahelpinghandtoprovideuserswithacustomized,dynamicresponse.DEFINITIONStaticcontentontheWebcomesdirectlyfromtextordatafiles,likeHTMLorJPEGfiles.Thesefilesmightbechangedfromtimetotime,buttheyarenotalteredautomaticallywhenrequestedbyawebbrowser.Dynamiccontent,ontheotherhand,isgeneratedonthefly,typicallyinresponsetoanindividualizedrequestfromabrowser.3.2.2CommonGatewayInterface(CGI)ThefirstwidelyusedstandardforproducingdynamiccontentwastheCommonGatewayInterface(CGI).CGIusesstandardoperatingsystemfeatures,suchasenvironmentvariablesandstandardinputandoutput,tocreateabridge,orgateway,betweenthewebserverandotherapplicationsonthehostmachine.Theotherapplicationscanlookattherequestsenttothembythewebserverandcreateacustomizedresponse.WhenawebserverreceivesarequestthatsintendedforaCGIprogram,itrunsthatprogramandprovidestheprogramwithinformationfromtheincomingrequest.TheCGIprogramrunsandsendsitsoutputbacktotheserver.Thewebserverthenrelaystheresponsetothebrowser.CGIdefinesasetofconventionsregardingwhatinformationitwillpassasenvironmentvariablesandhowitexpectsstandardinputandoutputtobeused.LikeHTTP,CGIisflexibleandeasytoimplement,andagreatnumberofCGI-awareprogramshavebeenwritten.ThemaindrawbacktoCGIisthatitmustrunanewcopyoftheCGI-awareprogramforeachrequest.Thisisarelativelyexpensiveprocessthatcanbogdownhigh-volumesiteswherethousandsofrequestsareservicedperminute.AnotherdrawbackisthatCGIprogramstendtobeplatformdependent.ACGIprogramwrittenforoneoperatingsystemmaynotrunonanother.3.2.3JavaservletsSunsJavaServletplatformdirectlyaddressesthetwomaindrawbacksofCGIprograms.First,servletsofferbetterperformanceandutilizationofresourcesthanconventionalCGIprograms.Second,thewrite-once,run-anywherenatureofJavameansthatservletsareportablebetweenoperatingsystemsthathaveaJavaVirtualMachine(JVM).Aservletlooksandfeelslikeaminiaturewebserver.Itreceivesarequestandrendersaresponse.But,unlikeconventionalwebservers,theservletapplicationprogramminginterface(API)isspecificallydesignedtohelpJavadeveloperscreatedynamicapplications.TheservletitselfissimplyaJavaclassthathasbeencompiledintobytecode,likeanyotherJavaobject.TheservlethasaccesstoarichAPIofHTTP-specificservices,butitisstilljustanotherJavaobjectrunninginanapplicationandcanleverageallyourotherJavaassets.Togiveconventionalwebserversaccesstoservlets,theservletsarepluggedintocontainers.Theservletcontainerisattachedtothewebserver.EachservletcandeclarewhatURLpatternsitwouldliketohandle.Whenarequestmatchingaregisteredpatternarrives,thewebserverpassestherequesttothecontainer,andthecontainerinvokestheservlet.ButunlikeCGIprograms,anewservletisnotcreatedforeachrequest.Oncethecontainerinstantiatestheservlet,itwilljustcreateanewthreadforeachrequest.JavathreadsaremuchlessexpensivethantheserverprocessesusedbyCGIprograms.Oncetheservlethasbeencreated,usingitforadditionalrequestsincursnverylittleoverhead.Servletdeveloperscanusetheinit()methodtoholdreferencestoexpensiveresources,suchasdatabaseconnectionsorEJBHomeInterfaces,sothattheycanbesharedbetweenrequests.Acquiringresourceslikethesecantakeseveralsecondswhichislongerthanmanysurfersarewillingtowait.Theotheredgeoftheswordisthat,sinceservletsaremultithreaded,servletdevelopersmusttakespecialcaretobesuretheirservletsarethread-safe.Tolearnmoreaboutservletprogramming,werecommendJavaServletsbyExample,byAlanR.WilliamsonWilliamson.ThedefinitivesourceforServletinformationistheJavaServletSpecificationSun,JST.3.2.4JavaServerPagesWhileJavaservletsareabigstepupfromCGIprograms,theyarenotapanacea.Togeneratetheresponse,developersarestillstuckwithusingprintlnstatementstorendertheHTML.Codethatlookslikeout.println(OnelineofHTML.);out.println(AnotherlineofHTML.);isalltoocommoninservletsthatgeneratetheHTTPresponse.TherearelibrariesthatcanhelpyougenerateHTML,butasapplicationsgrowmorecomplex,JavadevelopersendupbeingcastintotheroleofHTMLpagedesigners.Meanwhile,giventhechoice,mostprojectmanagersprefertodividedevelopmentteamsintospecializedgroups.TheylikeHTMLdesignerstobeworkingonthepresentationwhileJavaengineerssweatthebusinesslogic.Usingservletsaloneencouragesmixingmarkupwithbusinesslogic,makingitdifficultforteammemberstospecialize.Tosolvethisproblem,Sunturnedtotheideaofusingserverpagestocombinescriptingandtemplatingtechnologiesintoasinglecomponent.TobuildJava-ServerPages,developersstartbycreatingHTMLpagesinthesameoldway,usingthesameoldHTMLsyntax.Tobringdynamiccontentintothepage,thedevelopercanalsoplaceJSPscriptingelementsonthepage.ScriptingelementsaretagsthatencapsulatelogicthatisrecognizedbytheJSP.YoucaneasilypickoutscriptingelementsonJSPpagesbylookingforcodethatbeginswith.Forinstance,todisplaythelastmodifieddateonthepage,thedeveloperwouldplacethefollowingcodeinthepage:ThispagewasaccessedatTherearethreedifferenttypesofscriptingelements:expressions,scriptlets,anddeclarations,asshownintable1.1.Table1.1JSPscriptingelementsElementPurposeExpressionsJavacode,boundby,usedtoevaluateJavalanguagestatementsandinserttheresultintotheservletsoutputScriptletsJavacode,boundby,oftenusedtocreatedynamiccontentDeclarationsJavacode,boundby,usedtoaddcodetothebodyoftheservletclass3.3Enablingtechnologies11TobeseenasaJSPpage,thefilejustneedstobesavedwithanextensionof.jsp.WhenaclientrequeststheJSPpage,thecontainertranslatesthepageintoasourcecodefileforaJavaservletandcompilesthesourceintoaJavaclassfilejustasyouwoulddoifyouwerewritingaservletfromscratch.Atruntime,thecontainercanalsocheckthelastmodifieddateoftheJSPfileagainsttheclassfile.IftheJSPfilehaschangedsinceitwaslastcompiled,thecontainerwillretranslateandrebuildthepagealloveragain.ProjectmanagerscannowassignthepresentationlayertoHTMLdevelopers,whothenpassontheirworktoJavadeveloperstocompletethebusiness-logicportion.TheimportantthingtorememberisthataJSPpageisreallyjustaservlet.Anythingyoucandowithaservlet,youcandowithaJSP.3.3.1JSPtagsScriptingelementsareonlyoneofthetwowaystogeneratedynamicJSPcontent.Scriptletsarequick,easy,andpowerfulbutrequirethatdevelopersmixJavacodewithHTML.ExperiencehastaughtusthatembeddinglogicintoJSPpagesleadstonon-maintainableapplicationswithminimalopportunityforreuse.ApopularalternativeistouseJSPtags.JSPtagsaremixedinwiththeHTMLmarkupandcanbeusedasiftheywereordinaryHTMLtags.AsingleJSPtagmayrepresentdozensofJavastatements,butallthedeveloperneedstoknowistohowtoinsertthetag.TheprogrammingcodeishiddenawayinaJavaclassfile.Tousethesamecodeonanotherpage,thedeveloperonlyhastoinsertthetagmarkupagain.Ifthecodeforthetagchanges,allthetagswillautomaticallyusetheupdatedversion.TheJSPpageusingthetagdoesnotneedtoberevised.JSPtagsprovidemuchbetterreusethanscriptletsandcanbeeasierforpagedevelopers3.3.2JSPsvs.ASPsMicrosoftandSunbothoffertheirownbrandofserverpages.SunoffersJavaServerPagesandMicrosoftoffersActiveServerPages(ASP).BothJSPsandASPsaredesignedsothatdeveloperscancreatedynamicwebpagescustomizedwithback-officedata.Whilesimilaronthesurface,thereareseveraldifferencesbetweenASPsandJSPs:_JSPsareplatformindependentwriteonce,runanywhere._DevelopershaveinputtothedirectionofJSPsthroughtheJavaCommunityProcess(JCP)._JSPdeveloperscanextendtheJSPtagsetwithcustomtags._JavaBeansandEnterpriseJavaBeans(EJB)canbeusedwithJSPstoincreasereusabilityandreducemaintenance._JSPscanaccessmanyotherJavalibraries,includingJavaDatabaseConnectivity(JDBC),JavaMail,JavaMessageService(JMS),andJavaNamingandDirectoryInterface(JNDI)._JSPsarecompiledintoabinaryclassfileanddonotneedtobeinterpretedforeveryrequest._JSPsfindwidesupportwithtoolvendors,containers,andwebservers.touse,sincetheylooklikethefamiliarHTMLtags.AnumberofprebuiltJSPtagslibrariesareavailablethatwillperformusefulfunctionalityfordevelopers.AmongtheseisthenewJSPStandardTagLibrary(JSTL).ThisnewstandardprovidesarichlibraryofreusableJSPtags.FormoreonJSTL,wehighlyrecommendJSTLinAction,byShawnBayernBayern.StrutsworkswellwithJSTLandotherpubliclyavailabletaglibraries,aswellasanyyoumightwriteyourself.FormoreonJSPandJSPpages,wehighlyrecommendWebDevelopmentwithJavaServerPages,byDuaneK.Fields,MarkA.Kolb,andShawnBayernFields.ThedefinitivesourceforJSPinformationistheJavaServerPagesSpecificationSun,JSP.JSPpagesareanintegralpartoftheStrutsdeveloperstoolbox.MostStrutsdevelopersuseJSPpagesandcustomtagstocreateallthedynamiccontentfortheirapplications.3.3.3JavaBeansJavaBeansareJavaclasseswhichconformtoasetofdesignpatternsthatmakethemeasiertousewithdevelopmenttoolsandothercomponents.DEFINITIONAJavaBeanisareusablesoftwarecomponentwritteninJava.ToqualifyasaJavaBean,theclassmustbeconcreteandpublic,andhaveanoargumentconstructor.JavaBeansexposeinternalfieldsaspropertiesbyprovidingpublicmethodsthatfollowaconsistentdesignpattern.Knowingthatthepropertynamesfollowthispattern,otherJavaclassesareabletouseintrospectiontodiscoverandmanipulateJavaBeanproperties.Rollingyourown1Createaclassthatimplementsjavax.servlet.jsp.tagext.TagSupportorjavax.servlet.jsp.tagext.BodyTagSupportbyimplementingthedoStart()ordoEnd()method.ThesemethodsobtainaJspWriterobjecttowriteoutanyvalidHTMLcontentyouneed.2Createataglibrarydescriptor(TLD)filetomaptheclassesyoujustcreatedtoaJSPtagname.3Defineyourelementsinthewebapplicationdescriptorfile(web.xml).TelltheJSPpagethatyouwillbeusingyourtagsbyplacingataglibstatementatthetopofthepage:4Thisstatementimportsthelibraryforuseonthispageandassignsitatagprefix.Formore,seetheJSPTagLibrarytechnologypage.3.4Enablingtechnologies111TheJavaBeandesignpatternsprovideaccesstothebeansinternalstatethroughtwoflavorsofmethods:accessorsareusedtoreadaJavaBeansstate;mutatorsareusedtochangeaJavaBeansstate.Mutatorsarealwaysprefixedwithlowercasetokense
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025财务管理代理合同模板
- 2025电子产品采购合同(通讯设备)
- 2025商务英语写作货物进口合同范本
- 杭州买房别墅合同范本
- 途家租赁合同范本
- 2025购销合同示范文本
- 浴室瓷砖租房合同范本
- 煤炭合同范本模板
- 政府文印合同范本
- 出具汇算报告合同范本
- 2025年公文核改竞赛试题及答案
- 有机硅行业面试攻略:高级岗位面试题库
- 2025历年退役军人考试题库及答案
- 第一二单元月考综合试卷(试题)四年级上册数学沪教版
- 2025级新生军训开训仪式动员大会
- 农产品质量安全标准体系与实施路径-洞察及研究
- 专利分级管理办法
- 中组部选调生管理办法
- 克痉方湿热敷:缺血性脑卒中后上肢肌肉痉挛康复新路径
- 血常规检验中的质量控制
- 高尿酸血症健康管理方案
评论
0/150
提交评论