spring mvc中文parti目錄與翻譯注記_第1頁
spring mvc中文parti目錄與翻譯注記_第2頁
spring mvc中文parti目錄與翻譯注記_第3頁
spring mvc中文parti目錄與翻譯注記_第4頁
spring mvc中文parti目錄與翻譯注記_第5頁
已閱讀5頁,還剩162頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

TableofPartI目錄與翻譯注記(TableofcontentsPartII:文檔內(nèi)容(DocumentationTableofPartI目錄與翻譯注記(TableofcontentsPartII:文檔內(nèi)容(Documentation1Servlet3.0下的處理一般的SpringMVC模型2Servlet3.0下的處理一般的SpringMVC模型2弱配置Spring3弱配置Spring3SpringMVC4.2.4.RELEASE中文文本項目翻譯的是SpringMVC官方4.2.4.RELEASE版本(截至16年6月23SpringMVC4.2.4.RELEASE中文文本項目翻譯的是SpringMVC官方4.2.4.RELEASE版本(截至16年6月23日最新版本為4.3.0)的文檔,包含原文檔第21章SpringMVC部分的全部內(nèi)容。本項目只為完成一份有品質(zhì)的翻在文檔上進行即時評論:在gitbook文檔上,鼠標劃過任何段落右側(cè),浮現(xiàn)號時點擊即SpringMVC4.2.4.RELEASE45此較慢。翻譯內(nèi)容是Spring4.1.3.RELEASE版5此較慢。翻譯內(nèi)容是Spring4.1.3.RELEASE版部分內(nèi)容,不包含SpringMVC翻譯部分,不包含SpringMVC翻譯。但已是1年為Spring中--目SpringWebMVC框架簡介目SpringWebMVC框架簡介主題themes6Servlet3.0下的MultipartResolver處理一般的SpringMVCServlet3.0下的MultipartResolver處理一般的SpringMVC配置SpringMVC7821.1SpringWebMVC框架簡Spring的模型-視圖21.1SpringWebMVC框架簡Spring的模型-視圖-控制器(MVC)框架是圍繞一個DispatcherServlet來設(shè)計的,這個了@Controller和@RequestMapping的類和方法,Spring為處理器方法提供了極其多樣靈活的配置。Spring3.0后的@PathVariable注解以及一些其他的特性,@Controller注解機制同時SpringWebMVCBobMartin所寫的“開閉原則(TheOpen-Closed你無法增強SpringMVC中的final如AbstractController.setSynchronizeOnSession()方法等。請參考10.6.1理解AOP代理一節(jié),其中解釋了AOP代理的相關(guān)知識,論述了為什么你不能對final方法進行增強。在SpingbMVSprinSpring的視圖解析也是設(shè)計得異常靈活。控制器一般負責(zé)準備一個Map模型、填充數(shù)據(jù)、返支持多種配置,包括通過文件擴展名、Accept內(nèi)容頭、bean、配置文件等的配置,甚至你還可以自己實現(xiàn)一個視圖解析器ViewResolver。模型(MVC中的M,model)其實是一個Map類型的接口,徹底地把數(shù)據(jù)從視圖技術(shù)中抽象分離了出來。你可以與基于模板的渲染921.1.1SpringWebMVC的新特SpringWeb21.1.1SpringWebMVC的新特SpringWebSpringWebFlowSWF意在成為web應(yīng)用中的頁面流(pageflow)個模塊是有益的。thatguidetheuserthroughcontrollednavigationsthatdrivebusinessSpring’swebmoduleincludesmanyuniquewebsupportClearseparationofroles.Eachrole—controller,validator,commandobject,formobject,modelobject,DispatcherServlet,handlermapping,viewresolver,andsoon—canbefulfilledbyaspecializedPowerfulandstraightforwardconfigurationofbothframeworkandapplicationclassesasJavaBeans.Thisconfigurationcapabilityincludeseasyreferencingacrosscontexts,suchasfromwebcontrollerstobusinessobjectsandvalidators.Adaptability,non-intrusiveness,andflexibility.Defineanycontrollermethodsignatureyouneed,possiblyusingoneoftheparameterannotations(suchas@RequestParam,@RequestHeader,@PathVariable,andmore)foragivenReusablebusinesscode,noneedforduplication.Useexistingbusinessobjectsascommandorformobjectsinsteadofmirroringthemtoextendaparticularframeworkbaseclass.Customizablebindingandvalidation.Typemismatchesasapplication-levelvalidationerrorsthatkeeptheoffendingvalue,localizeddateandnumberbinding,andsooninsteadofString-onlyformobjectswithmanualparsingandconversiontobusinessobjects.Customizablehandlermappingandviewresolution.HandlermappingandviewresolutionstrategiesrangefromsimpleURL-basedconfiguration,tosophisticated,purpose-builtresolutionstrategies.SpringismoreflexiblethanwebMVCframeworksthatmandateaparticulartechnique.Flexiblemodeltransfer.Modeltransferwithaname/valueMapsupportsintegrationwithanyintegrationwithanyviewCustomizablelocale,timezoneandthemeresolution,supportforJSPswithorwithoutSpringtaglibrary,supportforJSTL,supportforVelocitywithouttheneedforextrabridges,andsoon.AsimpleyetpowerfulJSPtaglibraryknownastheSpringtaglibrarythatprovidessupportforfeaturessuchasdatabindingandthemes.Thecustomtagsallowformaximumflexibilityintermsofmarkupcode.Forinformationonthetaglibrarydescriptor,seetheappendixentitledChapter42,springJSPTagLibraryAJSPformtaglibrary,introducedinSpring2.0,thatmakeswritingformsinJSPpagesmucheasier.Forinformationonthetaglibrarydescriptor,seetheappendixentitledChapter43,spring-formJSPTagLibraryBeanswhoselifecycleisscopedtothecurrentHTTPrequestorHTTPSession.ThisisnotaspecificfeatureofSpringMVCitself,butratheroftheWebApplicationContextcontainer(s)thatSpringMVCuses.ThesebeanscopesaredescribedinSection6.5.4,“Request,session,andglobalsession允許其他MVC實允許其他MVC實Non-SpringMVCimplementationsarepreferableforsomeprojects.Manyteamsexpectleveragetheirexistinginvestmentinskillsandtools,forexamplewithIfyoudonotwanttouseSpring’sWebMVC,butintendtoleverageothersolutionsthatSpringoffers,youcanintegratethewebMVCframeworkofyourchoicewithSpringeasily.SimplystartupaSpringrootapplicationcontextthroughitsContextLoaderListener,andaccessitthroughitsServletContextattribute(orSpring’srespectivehelpermethod)fromwithinanyactionobject.No"plug-ins"areinvolved,sonodedicatedintegrationisnecessary.Fromtheweblayer’spointofview,yousimplyuseSpringasalibrary,withtherootapplicationcontextinstanceastheentryYourregisteredbeansandSpring’sservicescanbeatyourfingertipsevenwithoutSpring’sWebMVC.Springdoesnotcompetewithotherwebframeworksinthisscenario.ItsimplyaddressesthemanyareasthatthepurewebMVCframeworksdonot,frombeanconfigurationtodataaccessandtransactionhandling.SoyoucanenrichyourapplicationwithaSpringmiddletierand/ordataaccesstier,evenifyoujustwanttouse,forexample,thetransactionabstractionwithJDBCor21.2Spring’swebMVCframeworkis,likemanyotherweb21.2Spring’swebMVCframeworkis,likemanyotherwebMVCframeworks,request-driven,designedaroundacentralServletthatdispatchesrequeststocontrollersandoffersotherfunctionalitythatfacilitatesthedevelopmentofwebapplications.Spring’sDispatcherServlethowever,doesmorethanjustthat.ItiscompletelyintegratedwiththeSpringIoCcontainerandassuchallowsyoutouseeveryotherfeaturethatSpringMVSpringbMVCServleSprintSpingTherequestprocessingworkflowoftheSpringWebMVCDispatcherServletisillustratedinthefollowingdiagram.Thepattern-savvyreaderwillrecognizethattheDispatcherServletisanexpressionofthe"FrontController"designpattern(thisispatternthatSpringWebMVCshareswithmanyotherleadingweb下面這張圖展示了SpringWebMVCTheDispatcherServletisanactualServlet(itinheritsfromtheHttpServletbaseclass),andassuchisdeclaredintheweb.xmlofyourwebapplication.YouneedtomaprequeststhatyouwanttheDispatcherServlettohandle,byusingaURLmappinginthesameweb.xmlfile.ThisisstandardJavaEEServletconfiguration;thefollowingexampleshowssuchaDispatcherServletdeclarationand(它繼承自HttpServlet基類),它也是在你的TheDispatcherServletisanactualServlet(itinheritsfromtheHttpServletbaseclass),andassuchisdeclaredintheweb.xmlofyourwebapplication.YouneedtomaprequeststhatyouwanttheDispatcherServlettohandle,byusingaURLmappinginthesameweb.xmlfile.ThisisstandardJavaEEServletconfiguration;thefollowingexampleshowssuchaDispatcherServletdeclarationand(它繼承自HttpServlet基類),它也是在你的配置文件下聲明的。同樣,你需要在web.xml望處理的請求映射到對應(yīng)的URL上去。這就是標準的JavaEEServletIntheprecedingexample,allrequestsstartingwith/examplewillbehandledbyinstancenamedexample.InaServlet3.0+environment,youhavetheoptionofconfiguringtheServletcontainerprogrammatically.Belowisthebasedequivalentoftheaboveweb.xml開頭的請求都會被DispatcherServlet該。在Servlet3.0+>WebApplicationInitializerisaninterfaceprovidedbySpringMVCthatensuresyourcode-basedconfigurationisdetectedandautomaticallyusedtoinitializeanyWebApplicationInitializerisaninterfaceprovidedbySpringMVCthatensuresyourcode-basedconfigurationisdetectedandautomaticallyusedtoinitializeanyServlet3container.AnabstractbaseclassimplementationofthisinterfacenamedAbstractDispatcherServletInitializermakesiteveneasiertoregistertheDispatcherServletbysimplyspecifyingitsservletmapping.SeeCode-basedServletcontainerinitializationformore現(xiàn)AbstractDispatcherServletInitializer,它簡化了DispatcherServlet的注冊工作,你只需TheaboveisonlythefirststepinsettingupSpringWebMVC.YounowneedconfigurethevariousbeansusedbytheSpringWebMVCframework(overandabovetheDispatcherServletitself).WebMVC框架使用到(除了DispatcherServlet以外的其他bean)AsdetailedinSection6.15,“AdditionalCapabilitiesoftheApplicationContext”,ApplicationContextinstancesinSpringcanbescoped.IntheWebMVCframework,eachDispatcherServlethasitsownWebApplicationContext,whichinheritsallthebeansalreadydefinedintherootWebApplicationContext.Theseinheritedbeanscanbeoverriddenintheservlet-specificscope,andyoucandefinenewscope-specificbeanslocaltoagivenServlet6.15節(jié)“AdditionalCapabilitiesoftheApplicationContext(ApplicationContext的其他作用)”中我們聊到,ApplicationContext實例是可以有范圍(scope)的。在WebMVC框架中,每個DispatcherServlet都持有一個自己的上下文對象WebApplicationContextpublicclassMyWebApplicationInitializerimplementsWebApplicationInitializerpublicvoidonStartup(ServletContextcontainer)ServletRegistration.Dynamicregistration=container.addServlet("dispatcher",newDispatcherServlet());}}根WebApplicationContext對象中已經(jīng)定義的所有bean。這些繼承的bean可以在每個servlet的根WebApplicationContext對象中已經(jīng)定義的所有bean。這些繼承的bean可以在每個servlet的UponinitializationofaDispatcherServlet,SpringMVClooksforafilenamed[servlet-name]-servlet.xmlintheWEB-INFdirectoryofyourwebapplicationandcreatesthebeansdefinedthere,overridingthedefinitionsofanybeansdefinedwiththesamenameintheglobal在ConsiderthefollowingDispatcherServletServletconfiguration(intheweb.xmlWiththeaboveServletconfigurationinplace,youwillneedtoWiththeaboveServletconfigurationinplace,youwillneedtohaveafilecalled/WEB-INF/golfing-servlet.xmlinyourapplication;thisfilewillcontainallofyourSpringWebMVC-specificcomponents(beans).YoucanchangetheexactlocationofthisconfigurationfilethroughaServletinitializationparameter(seebelowfor文件,該文件必須包含所有SpringWebMVC相關(guān)的組件的定義(個ItisalsopossibletohavejustonerootcontextforsingleDispatcherServlet>ThiscanbeconfiguredbyThiscanbeconfiguredbysettinganemptycontextConfigLocationservletparameter,asshownTheWebApplicationContextisanextensionoftheplainApplicationContextthathassomeextrafeaturesnecessaryforwebapplications.ItdiffersfromanormalApplicationContextinthatitiscapableofresolvingthemes(seeSection21.9,“Usingthemes”),andthatitknowsTheWebApplicationContextisanextensionoftheplainApplicationContextthathassomeextrafeaturesnecessaryforwebapplications.ItdiffersfromanormalApplicationContextinthatitiscapableofresolvingthemes(seeSection21.9,“Usingthemes”),andthatitknowswhichServletitisassociatedwith(byhavingalinktotheServletContext).TheWebApplicationContextisboundintheServletContext,andbyusingstaticmethodsontheRequestContextUtilsclassyoucanalwayslookuptheWebApplicationContextifyouneedaccessto繼承自ApplicationContext,包含了一些web個的引用來實現(xiàn))。WebApplicationContext下文WebApplicationContext>TheSpringDispatcherServletusesspecialbeanstoprocessrequestsandrendertheappropriateviews.ThesebeansarepartofSpringMVC.YoucanchoosewhichspecialbeanstousebysimplyconfiguringoneormoreofthemintheWebApplicationContext.However,youdon’tneedtodothatinitiallysinceSpringMVCmaintainsalistofdefaultbeanstouseifyoudon’tconfigureany.Moreonthatinthenextsection.FirstseethetablebelowlistingthespecialbeantypestheDispatcherServletrelies在WebApplicationContext中簡單地配置它們(沒有忠于原文)。當然,這不是必須的,因為SpringMVC維護了一個默認的bean列表,如果你沒有進行特別的配置,框架將會使用默認的bean。下一小節(jié)會介紹更多的細節(jié),這里,我們將先快速地看一下,DispatcherServlet都依BeanMapsincomingrequeststohandlersandaBeanMapsincomingrequeststohandlersandalistofpre-andpost-processors(handlerinterceptors)basedonsomecriteriathedetailsofwhichvarybyHandlerMappingimplementation.Themostpopularimplementationsupportsannotatedcontrollersbutotherimplementationsexistsaswell.HelpstheDispatcherServlettoinvokeahandlermappedtoarequestregardlessofthehandlerisactuallyinvoked.Forexample,invokinganannotatedcontrollerrequiresresolvingvariousannotations.ThusthemainpurposeofaHandlerAdapteristoshieldtheDispatcherServletfromsuchdetails.Mapsexceptionstoviewsalsoallowingformorecomplexexceptionhandlingcode.ResolveslogicalString-basedviewnamestoactualViewtypes.LocaleResolverResolvesthelocaleaclientisusingandpossiblytheirtimezone,inordertobeabletoofferinternationalizedviews.Resolvesthemesyourwebapplicationcanuse,forexample,toofferpersonalizedlayouts.Parsesmulti-partrequestsforexampletosupportprocessingfileuploadsfromHTMLforms.Storesandretrievesthe"input"andthe"output"FlashMapthatcanbeusedtopassattributesfromonerequesttoanother,usuallyacrossa以及一系列前處理器和后處理器(hanlderinterceptors)上。具體的規(guī)則視HandlerMapping類的實現(xiàn)不同而有所不以及一系列前處理器和后處理器(hanlderinterceptors)上。具體的規(guī)則視HandlerMapping類的實現(xiàn)不同而有所不DispatcherServlet調(diào)用到負責(zé)處理某個具體請求的處因此,HandlerAdapter的主要任務(wù)就是DispatcherServlet從這些具體的細節(jié)中解放出來,交給LocaleResolver能夠存儲并取回負責(zé)輸入輸出(inputandFlashMap對象。后者可用于在請求之間傳遞數(shù)據(jù),通常21.2.2默認的DispatcherServlet配Asmentionedintheprevioussection21.2.2默認的DispatcherServlet配Asmentionedintheprevioussectionforeachspecialbeanthemaintainsalistofimplementationstousebydefault.ThisinformationiskeptintheDispatcherSpertiesinthepackageorg.springframework.web.servlet正如前一個小節(jié)所描述的,DispatcherServlet維護了一個列表,其中保存了所有依賴的的一個默認實現(xiàn)。這份信息配置在包org.springframework.web.servlet下的DispatcherSperties中.Allspecialbeanshavesomereasonabledefaultsoftheirown.Soonerorlaterthoughyou’llneedtocustomizeoneormoreofthepropertiesthesebeansprovide.Forexampleit’squitecommontoconfigureanInternalResourceViewResolversettingsitsprefixpropertytotheparentlocationofview屬性進行配置,比如說一個很常用的定制是,通過配置InternalResourceViewResolver類中的prefix屬性,使其指向視圖文件所在的目錄。Regardlessofthedetails,theimportantconcepttounderstandhereisthatonceyouconfigureaspecialbeansuchasanInternalResourceViewResolverinyourWebApplicationContext,youeffectivelyoverridethelistofdefaultimplementationsthatwouldhavebeenusedotherwiseforthatspecialbeantype.ForexampleifyouconfigureanInternalResourceViewResolver,thedefaultlistofViewResolverimplementationsis置了InternalResourceViewResolver,那么InSection21.16,“ConfiguringSpringMVC”you’lllearnaboutotheroptionsforconfiguringSpringMVCincludingMVCJavaconfigandtheMVCXMLnamespacebothofwhichprovideasimplestartingpointandassumelittleknowledgeofhowSpringMVCworks.Regardlessofhowyouchoosetoconfigureyourapplication,theconceptsexplainedinthissectionarefundamentalshouldbeofhelpto在21.16節(jié)“SpringMVC的配置”中,你可以了解到對SpringMVC進行配置的其他方式,比如21.2.3DispatcherServlet的處理流Afteryousetup,andarequest21.2.3DispatcherServlet的處理流Afteryousetup,andarequestcomesinforthatDispatcherServlet,theDispatcherServletstartsprocessingtherequestas配置好DispatcherServlet以后,當有請求經(jīng)過這個DispatcherServletTheWebApplicationContextissearchedforandboundintherequestasanattributethatthecontrollerandotherelementsintheprocesscanuse.ItisboundbydefaultunderthekeyDispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE.Thelocaleresolverisboundtotherequesttoenableelementsintheprocesstoresolvethelocaletousewhenprocessingtherequest(renderingtheview,preparingdata,andsoon).Ifyoudonotneedlocaleresolving,youdonotneedit.Thethemeresolverisboundtotherequesttoletelementssuchasviewsdeterminewhichthemetouse.Ifyoudonotusethemes,youcanignoreit.Ifyouspecifyamultipartfileresolver,therequestisinspectedformultiparts;ifmultipartsarefound,therequestiswrappedinaMultipartHttpServletRequestforfurtherprocessingbyotherelementsintheprocess.SeeSection21.10,“Spring’smultipart(fileupload)support”forfurtherinformationaboutmultiparthandling.Anappropriatehandlerissearchedfor.Ifahandlerisfound,theexecutionchainassociatedwiththehandler(preprocessors,postprocessors,andcontrollers)isexecutedinordertoprepareamodelorrendering.Ifamodelisreturned,theviewisrendered.Ifnomodelisreturned,(maybeduetoapreprocessororpostprocessorinterceptingtherequest,perhapsforsecurityreasons),noviewisrendered,becausetherequestcouldalreadyhavebeen默認以鍵名DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE被綁定到請求上(ereslveult,HandlerexceptionresolversthataredeclaredintheWebApplicationContextpickupexceptionsthatarethrownduringprocessingoftherequest.UsingtheseresolversallowsyoutodefinecustombehaviorstoaddressTheSpringDispatcherServletalsosupportsthereturnofthelast-modification-date,asspecifiedbytheServletAPI.Theprocessofdeterminingthelastmodificationdateforaspecificrequestisstraightforward:theDispatcherServletlooksupanappropriatehandlermappingandtestswhetherthehandlerthatisfoundimplementstheLastModifiedinterface.Ifso,thevalueofthelonggetLastModified(request)methodoftheLastModifiedinterfaceisreturnedtothe映射表來找到請求對應(yīng)的處理器,檢測它是否實現(xiàn)了LastModified的longgetLastModified(requestYoucancustomizeindividualDispatcherServletinstancesbyaddingServletinitializationparameters(init-paramelements)totheServletdeclarationintheweb.xmlfile.Seethefollowingtableforthelistofsupported你可以在servlet的定義文件web.xml文件中添加一些servlet的初始化參數(shù)(比如param等)來定制不同的DispatcherServlet任意實現(xiàn)了WebApplicationContext的類。這個類會初始化該個XmlWebApplicationContext對象給contextClass所指定的context實例對象進行解析。該字符任意實現(xiàn)了WebApplicationContext的類。這個類會初始化該個XmlWebApplicationContext對象給contextClass所指定的context實例對象進行解析。該字符的命名空間。默認是servlet-ClassthatimplementsWebApplicationContext,whichinstantiatesthecontextusedbythisServlet.Bydefault,theXmlWebApplicationContextisused.Stringthatispassedtothecontextinstance(specifiedbycontextClass)toindicatewherecontext(s)canbefound.Thestringconsistspotentiallyofmultiplestrings(usingacommaasadelimiter)tosupportmultiplecontexts.Incaseofmultiplecontextlocationswithbeansthataredefinedtwice,thelatestlocationtakesNamespaceoftheWebApplicationContext.Defaults[servlet-name]-servlet21.3控制器(controller)的實Controllersprovideaccesstotheapplicationbehaviorthatyou21.3控制器(controller)的實Controllersprovideaccesstotheapplicationbehaviorthatyoutypicallydefinethroughaserviceinterface.Controllersinterpretuserinputandtransformitintoamodelthatisrepresentedtotheuserbytheview.Springimplementsacontrollerinaveryabstractway,whichenablesyoutocreateawidevarietyof(mdeSpring2.5introducedanannotation-basedprogrammingmodelforMVCthatusesannotationssuch,,,andsoon.ThisannotationsupportisavailableforbothServletMVCandPortletMVC.Controllersimplementedinthisstyledonothavetoextendspecificbaseclassesorimplementspecificinterfaces.Furthermore,theydonotusuallyhavedirectdependenciesonServletorPortletAPIs,althoughyoucaneasilyconfigureaccesstoServletorPortlet了@RequestMapping、@RequestParam、@ModelAttribute等注解來支持MVC的控制器實現(xiàn)。Availableinthespring-projectsOrgonGithub,anumberofwebapplicationsleveragetheannotationsupportdescribedinthissectionincludingMvcShowcase,MvcAjax,MvcBasic,PetClinic,PetCare,andAsyoucansee,the@Controllerand@RequestMappingannotationsallowflexiblemethodnamesandsignatures.InthisparticularexamplethemethodacceptsaAsyoucansee,the@Controllerand@RequestMappingannotationsallowflexiblemethodnamesandsignatures.InthisparticularexamplethemethodacceptsaModelandreturnsaviewnameasaString,butvariousothermethodparametersandreturnvaluescanbeusedasexplainedlaterinthissection.@Controllerand@RequestMappingandanumberofotherannotationsformthebasisfortheSpringMVCimplementation.ThissectiondocumentstheseannotationsandhowtheyaremostcommonlyusedinaServlet從上面的例子可以看到,@Controller注解和@RequestMapping注解使得方法名和方法簽名的選擇變得更加靈活。在上面這個例子中,方法接受一個Model類型的參數(shù)并返回一個字符串String類型的視圖名,但事實上,方法可以接受的參數(shù)和返回值有更多的選擇,這個我們在本小節(jié)的后面部分會提及。@Controller和@RequestMapping及其他的一些注解,共同構(gòu)成publicclassHelloWorldControllerpublicStringhelloWorld(Model{model.addAttribute("message","HelloWorld!");return"helloWorld";}}21.3.1使用@Controller注解定義一個控制[Original]The@Controllerannotation21.3.1使用@Controller注解定義一個控制[Original]The@Controllerannotationindicatesthataparticularclassservestheroleofacontroller.SpringdoesnotrequireyoutoextendanycontrollerbaseclassorreferencetheServletAPI.However,youcanstillreferenceServlet-specificfeaturesifyouneed[Original]The@Controllerannotationactsasastereotypefortheannotatedclass,indicatingitsrole.Thedispatcherscanssuchannotatedclassesformappedmethodsanddetects@RequestMappingannotations(seethenext分派器(DispatcherServlet)會掃描所有注解了@Controller過@RequestMapping注解配置的方法(詳見下一小節(jié))[Original]Youcandefineannotatedcontrollerbeansexplicitly,usingastandardSpringbeandefinitioninthedispatcher’scontext.However,the@Controllerstereotypealsoallowsforautodetection,alignedwithSpringgeneralsupportfordetectingcomponentclassesintheclasspathandauto-registeringbeandefinitionsfor當然,你也可以不使用@Controller注解而顯式地去定義被注解的bean,這點通過標準的Springbean的定義方式,在dispather的上下文屬性下配置即可做到。但是@Controller原型[Original]Toenableautodetectionofsuchannotatedcontrollers,youaddcomponentscanningtoyourconfiguration.Usethespring-contextschemaasshowninthefollowingXML<?xmlversion="1.0"<?xmlversion="1.0"encoding="UTF-<beansxmlns="/schema/beans"<context:component-scanbase-<!--...--21.3.2使用@RequestMapping注解映射請路[Original]21.3.2使用@RequestMapping注解映射請路[Original]Youusethe@RequestMappingannotationtomapURLssuchontoanentireclassoraparticularhandlermethod.Typicallythelevelannotationmapsaspecificrequestpath(orpathpattern)ontoaformcontroller,withadditionalmethod-levelannotationsnarrowingtheprimarymappingforaspecificHTTPmethodrequestmethod("GET","POST",etc.)oranHTTPrequestparameter你可以使用@RequestMapping注解來將請求的URL(比如appointments之類的)路徑映射到[Original]ThefollowingexamplefromthePetcaresampleshowsacontrollerinaMVCapplicationthatusesthis[Original]Intheexample,[Original]Intheexample,the@RequestMappingisusedinanumberofplaces.Thefirstusageisonthetype(class)level,whichindicatesthatallhandlingmethodsonthiscontrollerarerelativetothe/appointmentspath.Theget()methodhasafurther@RequestMappingrefinement:itonlyacceptsGETrequests,meaningthatanHTTPGETfor/appointmentsinvokesthismethod.Theadd()hasasimilarrefinement,andthegetNewForm()combinesthedefinitionofHTTPmethodandpathintoone,sothatGETrequestsforappointments/newarehandledbythat(類)級別的,指示了該控制器下的所有處理方法都將以/appointments開頭。get(方法上publicclassAppointmentsController{privatefinalAppointmentBookpublicAppointmentsController(AppointmentBook{this.appointmentBook=}@RequestMapping(method=RequestMethod.GET)publicMap<String,Appointment>get(){return}@RequestMapping(path="/{day}",method=publicMap<String,Appointment>getForDay(@PathVariable@DateTimeFormat(iso=ISO.DATE)Dateday,Modelmodel){return}@RequestMapping(path="/new",method=RequestMethod.GET)publicAppointmentFormgetNewForm(){returnnew}@RequestMapping(method=publicStringadd(@ValidAppointmentFormappointment,BindingResult{if(result.hasErrors()){}return"redirect:/appointments";}}個請求路徑為/appointments的HTTPGET請求將會最終調(diào)用到這個方法。add方法也做了類似的細化,而getNewForm(方法則同時注解了能夠接受的請求的HTTP方法和路徑。在這種個請求路徑為/appointments的HTTPGET請求將會最終調(diào)用到這個方法。add方法也做了類似的細化,而getNewForm(方法則同時注解了能夠接受的請求的HTTP方法和路徑。在這種[Original]ThegetForDay()methodshowsanotherusageof@RequestMapping:templates.(Seethenext方法則展示了@RequestMapping注解的另一個作用:URI模板。(這個內(nèi)容請下節(jié)[Original]A@RequestMappingontheclasslevelisnotrequired.Withoutit,allpathsaresimplyabsolute,andnotrelative.ThefollowingexamplefromthePetClinicsampleapplicationshowsamulti-actioncontrollerusing@RequestMapping[Original]TheaboveexampledoesnotspecifyGETvs.PUT,POST,andsoforth,because@RequestMappingmapsallHTTPmethodsbydefault.Use@RequestMapping(method=GET)tonarrowthe以上代碼并不區(qū)分請求是GET方法還是PUT/POST或其他方法,因此@RequestMapping注解默)[Original]##@ControllerandAOPpublicclass{privatefinalClinicclinic;publicClinicController(Clinic{this.clinic=}publicvoidwelcomeHandler()}publicModelMapvetsHandler()returnnew}}[Original]InsomecasesacontrollermayneedtobedecoratedwithanAOPproxyatruntime.Oneexampleisifyouchoosetohave[Original]InsomecasesacontrollermayneedtobedecoratedwithanAOPproxyatruntime.Oneexampleisifyouchoosetohave@Transactionalannotationsdirectlyonthecontroller.Whenthisisthecase,forcontrollersspecifically,werecommendusingclass-basedproxying.Thisistypicallythedefaultchoicewithcontrollers.HoweverifacontrollermustimplementaninterfacethatisnotaSpringContextcallback(e.g.InitializingBean,*Aware,etc),youmayneedtoexplicitlyconfigureclass-basedproxying.Forexamplewith<tx:annotation-driven/>,changeto<tx:annotation-driven就是當你直接使用@Transactional注解來標注一個控制器的時候。如果——更多的時候是指控制器——但如果控制器同時必須實現(xiàn)另一些不支持SpringContext回調(diào)(比如InitializingBean由<tx:annotation-driven/改為tx:annotation-drivenproxy-target-class="true"/[Original]##NewSupportClassesfor@RequestMappingmethodsinSpringMVCSpringMVC3.1中新增支持@RequestMapping的[Original]Spring3.1introducedanewsetofsupportclassesfor@RequestMappingmethodscalledRequestMappingHandlerMappingandRequestMappingHandlerAdapterrespectively.TheyarerecommendedforuseandevenrequiredtotakeadvantageofnewfeaturesinSpringMVC3.1andgoingforward.ThenewsupportclassesareenabledbydefaultbytheMVCnamespaceandtheMVCJavaconfigbutmustbeconfiguredexplicitlyifusingneither.ThissectiondescribesafewimportantdifferencesbetweentheoldandthenewsupportSpring3.1中新增了一組支持@RequestMapping是RequestMappingHandlerMapping有些SpringMVC3.1之后的版本才新增的特性,這幾個注解甚至是必須的。不管是通過MVC[Original]PriortoSpring3.1,typeandmethod-levelrequestmappingswereintwoseparatestages[Original]PriortoSpring3.1,typeandmethod-levelrequestmappingswereintwoseparatestages—acontrollerwasselectedfirstbyandtheactualmethodtoinvokewasnarrowedsecondby.先DefaultAnnotationHanlderMapping會先選中一個控制器,然后再通[Original]WiththenewsupportclassesinSpring3.1,RequestMappingHandlerMappingistheonlyplacewhereadecisionismadeaboutwhichmethodshouldprocesstherequest.Thinkofcontrollermethodsasacollectionofuniqueendpointswithmappingsforeachmethodderivedfromtypeandmethod-level@RequestMapping現(xiàn)在有了Spring3.1后引入的這組新類,RequestMappingHandlerMapping成為了這兩個決策實[Original]Thisenablessomenewpossibilities.ForonceaHandlerInterceptororHandlerExceptionResolvercannowexpecttheObject-basedhandlertobe,whichallowsthemtoexaminetheexactmethod,itsparametersassociatedannotations.TheprocessingforaURLnolongerneedstobesplitdifferent的HandlerInterceptor或HandlerExceptionResolver現(xiàn)在可以確定拿到的這個處理器肯定是一個HandlerMethod類型,因此它能夠精確地了解這個方法的所有信息,包括它的參數(shù)、應(yīng)用于[Original]Therearealsoseveralthingsnolongerpossible:[Original]SelectacontrollerfirstwithaSimpleUrlHandlerMappingorBeanNameUrlHandlerMappingandthennarrowthemethodbasedon@RequestMappingannotations.[Original]Relyonmethodnamesasafall-backmechanismtodisambiguatebetweentwo@RequestMappingmethodsthatdon’thaveanexplicitpathmappingURLpathbutotherwisematchequally,e.g.byHTTPmethod.Inthenewsupportclasses@RequestMappingmethodshavetobemappeduniquely.[Original]*Haveasingledefaultmethod(withoutanexplicitpathmapping)withwhichrequestsareprocessedifnoothercontrollermethodmatchesmoreconcretely.Inthenewsupportclassesifamatchingmethodisnotfounda404erroris先通過SimpleUrlHandlerMapping或BeanNameUrlHandlerMapping來拿到負責(zé)處理請求的控制器,然后通過@RequestMapping注解配置的信息來定位

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論