版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
TableofPartI目录与翻译注记(TableofcontentsPartII:文档内容(DocumentationTableofPartI目录与翻译注记(TableofcontentsPartII:文档内容(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部分的全部内容。本项目只为完成一份有品质的翻在文档上进行即时评论:在gitbook文档上,鼠标划过任何段落右侧,浮现号时点击即SpringMVC4.2.4.RELEASE45此较慢。翻译内容是Spring4.1.3.RELEASE版5此较慢。翻译内容是Spring4.1.3.RELEASE版部分内容,不包含SpringMVC翻译部分,不包含SpringMVC翻译。但已是1年为Spring中--目SpringWebMVC框架简介目SpringWebMVC框架简介主题themes6Servlet3.0下的MultipartResolver处理一般的SpringMVCServlet3.0下的MultipartResolver处理一般的SpringMVC配置SpringMVC7821.1SpringWebMVC框架简Spring的模型-视图21.1SpringWebMVC框架简Spring的模型-视图-控制器(MVC)框架是围绕一个DispatcherServlet来设计的,这个了@Controller和@RequestMapping的类和方法,Spring为处理器方法提供了极其多样灵活的配置。Spring3.0后的@PathVariable注解以及一些其他的特性,@Controller注解机制同时SpringWebMVCBobMartin所写的“开闭原则(TheOpen-Closed你无法增强SpringMVC中的final如AbstractController.setSynchronizeOnSession()方法等。请参考10.6.1理解AOP代理一节,其中解释了AOP代理的相关知识,论述了为什么你不能对final方法进行增强。在SpingbMVSprinSpring的视图解析也是设计得异常灵活。控制器一般负责准备一个Map模型、填充数据、返支持多种配置,包括通过文件扩展名、Accept内容头、bean、配置文件等的配置,甚至你还可以自己实现一个视图解析器ViewResolver。模型(MVC中的M,model)其实是一个Map类型的接口,彻底地把数据从视图技术中抽象分离了出来。你可以与基于模板的渲染921.1.1SpringWebMVC的新特SpringWeb21.1.1SpringWebMVC的新特SpringWebSpringWebFlowSWF意在成为web应用中的页面流(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望处理的请求映射到对应的URL上去。这就是标准的JavaEEServletIntheprecedingexample,allrequestsstartingwith/examplewillbehandledbyinstancenamedexample.InaServlet3.0+environment,youhavetheoptionofconfiguringtheServletcontainerprogrammatically.Belowisthebasedequivalentoftheaboveweb.xml开头的请求都会被DispatcherServlet该。在Servlet3.0+>WebApplicationInitializerisaninterfaceprovidedbySpringMVCthatensuresyourcode-basedconfigurationisdetectedandautomaticallyusedtoinitializeanyWebApplicationInitializerisaninterfaceprovidedbySpringMVCthatensuresyourcode-basedconfigurationisdetectedandautomaticallyusedtoinitializeanyServlet3container.AnabstractbaseclassimplementationofthisinterfacenamedAbstractDispatcherServletInitializermakesiteveneasiertoregistertheDispatcherServletbysimplyspecifyingitsservletmapping.SeeCode-basedServletcontainerinitializationformore现AbstractDispatcherServletInitializer,它简化了DispatcherServlet的注册工作,你只需TheaboveisonlythefirststepinsettingupSpringWebMVC.YounowneedconfigurethevariousbeansusedbytheSpringWebMVCframework(overandabovetheDispatcherServletitself).WebMVC框架使用到(除了DispatcherServlet以外的其他bean)AsdetailedinSection6.15,“AdditionalCapabilitiesoftheApplicationContext”,ApplicationContextinstancesinSpringcanbescoped.IntheWebMVCframework,eachDispatcherServlethasitsownWebApplicationContext,whichinheritsallthebeansalreadydefinedintherootWebApplicationContext.Theseinheritedbeanscanbeoverriddenintheservlet-specificscope,andyoucandefinenewscope-specificbeanslocaltoagivenServlet6.15节“AdditionalCapabilitiesoftheApplicationContext(ApplicationContext的其他作用)”中我们聊到,ApplicationContext实例是可以有范围(scope)的。在WebMVC框架中,每个DispatcherServlet都持有一个自己的上下文对象WebApplicationContextpublicclassMyWebApplicationInitializerimplementsWebApplicationInitializerpublicvoidonStartup(ServletContextcontainer)ServletRegistration.Dynamicregistration=container.addServlet("dispatcher",newDispatcherServlet());}}根WebApplicationContext对象中已经定义的所有bean。这些继承的bean可以在每个servlet的根WebApplicationContext对象中已经定义的所有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相关的组件的定义(个ItisalsopossibletohavejustonerootcontextforsingleDispatcherServlet>ThiscanbeconfiguredbyThiscanbeconfiguredbysettinganemptycontextConfigLocationservletparameter,asshownTheWebApplicationContextisanextensionoftheplainApplicationContextthathassomeextrafeaturesnecessaryforwebapplications.ItdiffersfromanormalApplicationContextinthatitiscapableofresolvingthemes(seeSection21.9,“Usingthemes”),andthatitknowsTheWebApplicationContextisanextensionoftheplainApplicationContextthathassomeextrafeaturesnecessaryforwebapplications.ItdiffersfromanormalApplicationContextinthatitiscapableofresolvingthemes(seeSection21.9,“Usingthemes”),andthatitknowswhichServletitisassociatedwith(byhavingalinktotheServletContext).TheWebApplicationContextisboundintheServletContext,andbyusingstaticmethodsontheRequestContextUtilsclassyoucanalwayslookuptheWebApplicationContextifyouneedaccessto继承自ApplicationContext,包含了一些web个的引用来实现)。WebApplicationContext下文WebApplicationContext>TheSpringDispatcherServletusesspecialbeanstoprocessrequestsandrendertheappropriateviews.ThesebeansarepartofSpringMVC.YoucanchoosewhichspecialbeanstousebysimplyconfiguringoneormoreofthemintheWebApplicationContext.However,youdon’tneedtodothatinitiallysinceSpringMVCmaintainsalistofdefaultbeanstouseifyoudon’tconfigureany.Moreonthatinthenextsection.FirstseethetablebelowlistingthespecialbeantypestheDispatcherServletrelies在WebApplicationContext中简单地配置它们(没有忠于原文)。当然,这不是必须的,因为SpringMVC维护了一个默认的bean列表,如果你没有进行特别的配置,框架将会使用默认的bean。下一小节会介绍更多的细节,这里,我们将先快速地看一下,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)上。具体的规则视HandlerMapping类的实现不同而有所不以及一系列前处理器和后处理器(hanlderinterceptors)上。具体的规则视HandlerMapping类的实现不同而有所不DispatcherServlet调用到负责处理某个具体请求的处因此,HandlerAdapter的主要任务就是DispatcherServlet从这些具体的细节中解放出来,交给LocaleResolver能够存储并取回负责输入输出(inputandFlashMap对象。后者可用于在请求之间传递数据,通常21.2.2默认的DispatcherServlet配Asmentionedintheprevioussection21.2.2默认的DispatcherServlet配Asmentionedintheprevioussectionforeachspecialbeanthemaintainsalistofimplementationstousebydefault.ThisinformationiskeptintheDispatcherSpertiesinthepackageorg.springframework.web.servlet正如前一个小节所描述的,DispatcherServlet维护了一个列表,其中保存了所有依赖的的一个默认实现。这份信息配置在包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节“SpringMVC的配置”中,你可以了解到对SpringMVC进行配置的其他方式,比如21.2.3DispatcherServlet的处理流Afteryousetup,andarequest21.2.3DispatcherServlet的处理流Afteryousetup,andarequestcomesinforthatDispatcherServlet,theDispatcherServletstartsprocessingtherequestas配置好DispatcherServlet以后,当有请求经过这个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映射表来找到请求对应的处理器,检测它是否实现了LastModified的longgetLastModified(requestYoucancustomizeindividualDispatcherServletinstancesbyaddingServletinitializationparameters(init-paramelements)totheServletdeclarationintheweb.xmlfile.Seethefollowingtableforthelistofsupported你可以在servlet的定义文件web.xml文件中添加一些servlet的初始化参数(比如param等)来定制不同的DispatcherServlet任意实现了WebApplicationContext的类。这个类会初始化该个XmlWebApplicationContext对象给contextClass所指定的context实例对象进行解析。该字符任意实现了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的控制器实现。Availableinthespring-projectsOrgonGithub,anumberofwebapplicationsleveragetheannotationsupportdescribedinthissectionincludingMvcShowcase,MvcAjax,MvcBasic,PetClinic,PetCare,andAsyoucansee,the@Controllerand@RequestMappingannotationsallowflexiblemethodnamesandsignatures.InthisparticularexamplethemethodacceptsaAsyoucansee,the@Controllerand@RequestMappingannotationsallowflexiblemethodnamesandsignatures.InthisparticularexamplethemethodacceptsaModelandreturnsaviewnameasaString,butvariousothermethodparametersandreturnvaluescanbeusedasexplainedlaterinthissection.@Controllerand@RequestMappingandanumberofotherannotationsformthebasisfortheSpringMVCimplementation.ThissectiondocumentstheseannotationsandhowtheyaremostcommonlyusedinaServlet从上面的例子可以看到,@Controller注解和@RequestMapping注解使得方法名和方法签名的选择变得更加灵活。在上面这个例子中,方法接受一个Model类型的参数并返回一个字符串String类型的视图名,但事实上,方法可以接受的参数和返回值有更多的选择,这个我们在本小节的后面部分会提及。@Controller和@RequestMapping及其他的一些注解,共同构成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注解配置的方法(详见下一小节)[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请求将会最终调用到这个方法。add方法也做了类似的细化,而getNewForm(方法则同时注解了能够接受的请求的HTTP方法和路径。在这种个请求路径为/appointments的HTTPGET请求将会最终调用到这个方法。add方法也做了类似的细化,而getNewForm(方法则同时注解了能够接受的请求的HTTP方法和路径。在这种[Original]ThegetForDay()methodshowsanotherusageof@RequestMapping:templates.(Seethenext方法则展示了@RequestMapping注解的另一个作用:URI模板。(这个内容请下节[Original]A@RequestMappingontheclasslevelisnotrequired.Withoutit,allpathsaresimplyabsolute,andnotrelative.ThefollowingexamplefromthePetClinicsampleapplicationshowsamulti-actioncontrollerusing@RequestMapping[Original]TheaboveexampledoesnotspecifyGETvs.PUT,POST,andsoforth,because@RequestMappingmapsallHTTPmethodsbydefault.Use@RequestMapping(method=GET)tonarrowthe以上代码并不区分请求是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注解来标注一个控制器的时候。如果——更多的时候是指控制器——但如果控制器同时必须实现另一些不支持SpringContext回调(比如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现在有了Spring3.1后引入的这组新类,RequestMappingHandlerMapping成为了这两个决策实[Original]Thisenablessomenewpossibilities.ForonceaHandlerInterceptororHandlerExceptionResolvercannowexpecttheObject-basedhandlertobe,whichallowsthemtoexaminetheexactmethod,itsparametersassociatedannotations.TheprocessingforaURLnolongerneedstobesplitdifferent的HandlerInterceptor或HandlerExceptionResolver现在可以确定拿到的这个处理器肯定是一个HandlerMethod类型,因此它能够精确地了解这个方法的所有信息,包括它的参数、应用于[Original]Therearealsoseveralthingsnolongerpossible:[Original]SelectacontrollerfirstwithaSimpleUrlHandlerMappingorBeanNameUrlHandlerMappingandthennarrowthemethodbasedon@RequestMappingannotations.[Original]Relyonmethodnamesasafall-backmechanismtodisambiguatebetweentwo@RequestMappingmethodsthatdon’thaveanexplicitpathmappingURLpathbutotherwisematchequally,e.g.byHTTPmethod.Inthenewsupportclasses@RequestMappingmethodshavetobemappeduniquely.[Original]*Haveasingledefaultmethod(withoutanexplicitpathmapping)withwhichrequestsareprocessedifnoothercontrollermethodmatchesmoreconcretely.Inthenewsupportclassesifamatchingmethodisnotfounda404erroris先通过SimpleUrlHandlerMapping或BeanNameUrlHandlerMapping来拿到负责处理请求的控制器,然后通过@RequestMapping注解配置的信息来定位
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024年电力系统安装服务项目资金筹措计划书代可行性研究报告
- 上海市崇明县2024年一级造价工程师《土建计量》点睛提分卷含解析
- 2025年天津高中学业水平合格性考试政治试卷试题(含答案解析)
- 勤俭节约主题教育6
- 《数控机床加工工艺》课件
- 2024中小学食品安全工作计划
- 月现代信息技术工作计划
- XX镇2024年度安全生产监督检查工作计划
- 学年度第二学期小学安全工作计划范文
- 小学科学三年级下册教学计划
- 戒毒人员心理健康教育
- 审计法实施条例解读
- 2024 年学校教务副校长述职:以教育改革创新铸学校卓越发展
- 学生假期规划怎做
- 智慧旅游论文开题报告
- 2023年内蒙古恒正集团呼和浩特第三工贸有限公司招聘考试真题
- 苏州大学《自然语言处理》2021-2022学年期末试卷
- DB32T-中小学生健康管理技术规范 第1部分:心理健康
- 2024年“安全生产月”暨“安康杯”竞赛活动考试题库及答案
- 儿童毛细支气管炎管理临床实践指南 (2024版)
- 2024年七月医疗器械质量管理制度
评论
0/150
提交评论