0% found this document useful (0 votes)
213 views

Spring MVC

The document discusses Spring Web MVC, a model-view-controller framework for building web applications in Java. It describes key features of Spring Web MVC including clear separation of roles, powerful and straightforward configuration of classes, adaptability and flexibility, and reusable business code. The core of Spring Web MVC is the DispatcherServlet, which handles requests and dispatches them to controllers. It follows a front controller design pattern and integrates with the Spring Inversion of Control container.

Uploaded by

bvishwanathr
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
213 views

Spring MVC

The document discusses Spring Web MVC, a model-view-controller framework for building web applications in Java. It describes key features of Spring Web MVC including clear separation of roles, powerful and straightforward configuration of classes, adaptability and flexibility, and reusable business code. The core of Spring Web MVC is the DispatcherServlet, which handles requests and dispatches them to controllers. It follows a front controller design pattern and integrates with the Spring Inversion of Control container.

Uploaded by

bvishwanathr
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

2/3/2014

15. Web MVC framework

Prev

15.WebMVCframework PartV.TheWeb

Next

15.WebMVCframework 15.1IntroductiontoSpringWebMVCframework
The Spring Web modelviewcontroller (MVC) framework is designed around a D i s p a t c h e r S e r v l e t that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for uploading files. The default handler is based on the @ C o n t r o l l e r and @ R e q u e s t M a p p i n g annotations,offeringawiderangeofflexiblehandlingmethods.WiththeintroductionofSpring 3.0, the @ C o n t r o l l e r mechanism also allows you to create RESTful Web sites and applications, through the @ P a t h V a r i a b l e annotationandotherfeatures. In Spring Web MVC you can use any object as a command or formbackingobjectyoudonotneedtoimplementaframework specificinterface or base class. Spring's data binding is highly flexible: for example, it treats type mismatches as validation errors that can be evaluated by the application, not as system errors. Thus you need not duplicate your business objects' propertiesassimple,untypedstringsinyourformobjectssimply tohandleinvalidsubmissions,ortoconverttheStringsproperly. Instead, it is often preferable to bind directly to your business objects. Spring's view resolution is extremely flexible. A C o n t r o l l e r implementation can even write directly to the response stream. Typically,a M o d e l A n d V i e w instanceconsistsofaviewnameand a model M a p , which contains bean names and corresponding objects such as a command or form, which contain reference data.Viewnameresolutionishighlyconfigurable,throughbean names, a properties file, or your own V i e w R e s o l v e r implementation.Themodel(theMinMVC)isbasedonthe M a p interface, which allows for the complete abstraction of the view technology.YoucanintegratedirectlyJSP,Velocity,oranyother renderingtechnology.Themodel M a p issimplytransformedinto an appropriate format, such as JSP request attributes or a Velocitytemplatemodel.

Openforextension... A key design principle in Spring Web MVC and in Spring in general is the Open for extension, closed for modificationprinciple. Some methods in the core classes of SpringWebMVCaremarked f i n a l . As a developer you cannot override these methods to supply your own behavior. This has not been done arbitrarily, but specificallywiththisprincipalinmind. Foranexplanationofthisprinciple,refer to Expert Spring Web MVC and Web Flow by Seth Ladd and others specifically see the section "A Look At Design,"onpage117ofthefirst edition. Alternatively,see 1. Bob Martin, The OpenClosed Principle(PDF) You cannot add advice to final methods whenyouuseSpringMVC.Forexample, you cannot add advice to the A b s t r a c t C o n t r o l l e r . s e t S y n c h r o n i z e O n S e s s i o n ( ) method. Refer to Section 7.6.1, Understanding AOP proxies for more informationonAOPproxiesandwhyyou cannotaddadvicetofinalmethods.

15.1.1FeaturesofSpringWebMVC
Spring's web module includes manyuniqueweb supportfeatures: Clear separation of roles. Eachrole controller, validator, command object, form object, model object,

SpringWebFlow Spring Web Flow (SWF) aims to be the bestsolutionforthemanagementofweb applicationpageflow. SWFintegrateswithexistingframeworks likeSpringMVC,Struts,andJSF,inboth servlet and portlet environments. If you have a business process (or processes) that would benefit from a conversational model as opposed to a purely request model,thenSWFmaybethesolution. SWF allows you to capture logical page flowsasselfcontainedmodulesthat are reusable in different situations, and as suchisidealforbuildingweb application modules that guide the user through controllednavigationsthatdrivebusiness processes. FormoreinformationaboutSWF,consult theSpringWebFlowwebsite.

D i s p a t c h e r S e r v l e t ,handlermapping,viewresolver,andsooncanbefulfilledbyaspecializedobject.

PowerfulandstraightforwardconfigurationofbothframeworkandapplicationclassesasJavaBeans.This
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 1/30

2/3/2014

15. Web MVC framework

configuration capability includes easy referencing across contexts, such as from web controllers to businessobjectsandvalidators. Adaptability,nonintrusiveness,andflexibility.Defineanycontrollermethodsignatureyouneed,possibly usingoneoftheparameterannotations(suchas@RequestParam,@RequestHeader,@PathVariable,and more)foragivenscenario. Reusable business code, no need for duplication. Use existing business objects as command or form objectsinsteadofmirroringthemtoextendaparticularframeworkbaseclass. Customizablebindingandvalidation.Typemismatchesasapplicationlevelvalidationerrorsthatkeepthe offending value, localized date and number binding, and so on instead of Stringonly form objects with manualparsingandconversiontobusinessobjects. Customizablehandlermappingandviewresolution.Handlermappingandviewresolutionstrategiesrange fromsimpleURLbasedconfiguration,tosophisticated,purposebuiltresolutionstrategies.Springismore flexiblethanwebMVCframeworksthatmandateaparticulartechnique. Flexible model transfer. Model transfer with a name/value M a p supports easy integration with any view technology. Customizablelocaleandthemeresolution,supportforJSPswithorwithoutSpringtaglibrary,supportfor JSTL,supportforVelocitywithouttheneedforextrabridges,andsoon. AsimpleyetpowerfulJSPtaglibraryknownastheSpringtaglibrarythatprovidessupportforfeaturessuch asdatabindingandthemes.Thecustomtagsallowformaximumflexibilityintermsofmarkupcode.For informationonthetaglibrarydescriptor,seetheappendixentitledAppendixF,spring.tld AJSPformtaglibrary,introducedinSpring2.0,thatmakeswritingformsinJSPpagesmucheasier.For informationonthetaglibrarydescriptor,seetheappendixentitledAppendixG,springform.tld Beans whose lifecycle is scoped to the current HTTP request or HTTP S e s s i o n . This is not a specific featureofSpringMVCitself,butratherofthe W e b A p p l i c a t i o n C o n t e x t container(s)thatSpringMVCuses. ThesebeanscopesaredescribedinSection3.5.4,Request,session,andglobalsessionscopes

15.1.2PluggabilityofotherMVCimplementations
NonSpringMVCimplementationsarepreferableforsomeprojects.Manyteamsexpecttoleveragetheirexisting investmentinskillsandtools.AlargebodyofknowledgeandexperienceexistfortheStrutsframework.Ifyou canabideStruts'architecturalflaws,itcanbeaviablechoicefortheweblayerthesameappliestoWebWork andotherwebMVCframeworks. IfyoudonotwanttouseSpring'swebMVC,butintendtoleverageothersolutionsthatSpringoffers,youcan integratethewebMVCframeworkofyourchoicewithSpringeasily.SimplystartupaSpringrootapplication context through its C o n t e x t L o a d e r L i s t e n e r , and access it through its S e r v l e t C o n t e x t attribute (or Spring's respectivehelpermethod)fromwithinaStrutsorWebWorkaction.No"plugins"areinvolved,sonodedicated integrationisnecessary.Fromtheweblayer'spointofview,yousimplyuseSpringasalibrary,withthe root applicationcontextinstanceastheentrypoint. YourregisteredbeansandSpring'sservicescanbeatyourfingertipsevenwithoutSpring'sWebMVC.Spring doesnotcompetewithStrutsorWebWorkinthisscenario.Itsimplyaddressesthemanyareasthatthepureweb MVCframeworksdonot,frombeanconfigurationtodataaccessandtransactionhandling.Soyoucanenrich yourapplicationwithaSpringmiddletierand/ordataaccesstier,evenifyoujustwanttouse,forexample,the transactionabstractionwithJDBCorHibernate.

15.2TheD i s p a t c h e r S e r v l e t
Spring's web MVC framework is, like many other web MVC frameworks, requestdriven, designed around a centralservletthatdispatchesrequeststocontrollersandoffersotherfunctionalitythatfacilitatesthedevelopment ofwebapplications.Spring's D i s p a t c h e r S e r v l e t however,doesmorethanjustthat.Itiscompletelyintegrated withtheSpringIoCcontainerandassuchallowsyoutouseeveryotherfeaturethatSpringhas. The request processing workflow of the Spring Web MVC D i s p a t c h e r S e r v l e t is illustrated in the following diagram. The patternsavvy reader will recognize that the D i s p a t c h e r S e r v l e t is an expression of the Front Controller design pattern (this is a pattern that Spring Web MVC shares with many other leading web frameworks).

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

2/30

2/3/2014

15. Web MVC framework

TherequestingprocessingworkflowinSpringWebMVC(highlevel)

The D i s p a t c h e r S e r v l e t is an actual S e r v l e t (it inherits from the H t t p S e r v l e t base class), and as such is declaredinthew e b . x m l ofyourwebapplication.YouneedtomaprequeststhatyouwanttheD i s p a t c h e r S e r v l e t tohandle,byusingaURLmappinginthesame w e b . x m l file.ThisisstandardJ2EEservletconfigurationthe followingexampleshowssuchaD i s p a t c h e r S e r v l e t declarationandmapping:
< w e b a p p > < s e r v l e t > < s e r v l e t n a m e > e x a m p l e < / s e r v l e t n a m e > < s e r v l e t c l a s s > o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . D i s p a t c h e r S e r v l e t < / s e r v l e t c l a s s > < l o a d o n s t a r t u p > 1 < / l o a d o n s t a r t u p > < / s e r v l e t > < s e r v l e t m a p p i n g > < s e r v l e t n a m e > e x a m p l e < / s e r v l e t n a m e > < u r l p a t t e r n > * . f o r m < / u r l p a t t e r n > < / s e r v l e t m a p p i n g > < / w e b a p p >

In the preceding example, all requests ending with . f o r m will be handled by the e x a m p l e D i s p a t c h e r S e r v l e t . ThisisonlythefirststepinsettingupSpringWebMVC.Younowneedtoconfigurethevariousbeansusedby theSpringWebMVCframework(overandabovetheD i s p a t c h e r S e r v l e t itself). AsdetailedinSection3.13,AdditionalCapabilitiesoftheApplicationContext,A p p l i c a t i o n C o n t e x t instancesin Spring can be scoped. In the Web MVC framework, each D i s p a t c h e r S e r v l e t has its own W e b A p p l i c a t i o n C o n t e x t ,whichinheritsallthebeansalreadydefinedintheroot W e b A p p l i c a t i o n C o n t e x t .These inheritedbeanscanbeoverriddenintheservletspecificscope,andyoucandefinenewscopespecificbeans localtoagivenservletinstance.

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

3/30

2/3/2014

15. Web MVC framework

ContexthierarchyinSpringWebMVC

UponinitializationofaD i s p a t c h e r S e r v l e t ,theframeworklooksforafilenamed [ s e r v l e t n a m e ] s e r v l e t . x m l in the W E B I N F directoryofyourwebapplicationandcreatesthebeansdefinedthere,overridingthedefinitionsof anybeansdefinedwiththesamenameintheglobalscope. ConsiderthefollowingD i s p a t c h e r S e r v l e t servletconfiguration(inthew e b . x m l file):


< w e b a p p > < s e r v l e t > < s e r v l e t n a m e > g o l f i n g < / s e r v l e t n a m e > < s e r v l e t c l a s s > o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . D i s p a t c h e r S e r v l e t < / s e r v l e t c l a s s > < l o a d o n s t a r t u p > 1 < / l o a d o n s t a r t u p > < / s e r v l e t > < s e r v l e t m a p p i n g > < s e r v l e t n a m e > g o l f i n g < / s e r v l e t n a m e > < u r l p a t t e r n > / g o l f i n g / * < / u r l p a t t e r n > < / s e r v l e t m a p p i n g > < / w e b a p p >

Withtheaboveservletconfigurationinplace,youwillneedtohaveafilecalled / W E B I N F / golfings e r v l e t . x m l in your application this file will contain all of your Spring Web MVCspecific components (beans). You can change the exact location of this configuration file through a servlet initialization parameter (see below for details). The W e b A p p l i c a t i o n C o n t e x t is an extension of the plain A p p l i c a t i o n C o n t e x t that has some extra features necessary for web applications. It differs from a normal A p p l i c a t i o n C o n t e x t in that it is capable of resolving themes(seeSection15.7,Usingthemes),andthatitknowswhichservletitisassociatedwith(byhavingalink to the S e r v l e t C o n t e x t ). The W e b A p p l i c a t i o n C o n t e x t is bound in the S e r v l e t C o n t e x t , and by using static methodson the R e q u e s t C o n t e x t U t i l s class you can always look up the W e b A p p l i c a t i o n C o n t e x t if you need accesstoit. TheSpringD i s p a t c h e r S e r v l e t usesspecialbeanstoprocessrequestsandrendertheappropriateviews.These beans are part of Spring Framework. You can configure them in the W e b A p p l i c a t i o n C o n t e x t , just as you configureanyotherbean.However,formostbeans,sensibledefaultsareprovidedsoyouinitiallydonotneedto configurethem.Thesebeansaredescribedinthefollowingtable.

Table15.1.SpecialbeansintheW e b A p p l i c a t i o n C o n t e x t Beantype controllers handler mappings Explanation FormtheC partoftheMVC. Handletheexecutionofalistofpreprocessorsandpostprocessorsandcontrollersthat willbeexecutediftheymatchcertaincriteria(forexample,amatchingURLspecifiedwith thecontroller).
4/30

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

2/3/2014

15. Web MVC framework

view resolvers locale resolver Theme resolver multipart fileresolver handler exception resolvers

Resolvesviewnamestoviews. Alocaleresolverisacomponentcapableofresolvingthelocaleaclientisusing,inorder tobeabletoofferinternationalizedviews Athemeresolveriscapableofresolvingthemesyourwebapplicationcanuse,for example,toofferpersonalizedlayouts ContainsfunctionalitytoprocessfileuploadsfromHTMLforms. Containsfunctionalitytomapexceptionstoviewsorimplementothermorecomplex exceptionhandlingcode.

After you set up a D i s p a t c h e r S e r v l e t , and a request comes in for that specific D i s p a t c h e r S e r v l e t , the D i s p a t c h e r S e r v l e t startsprocessingtherequestasfollows: 1. TheW e b A p p l i c a t i o n C o n t e x t issearchedforandboundintherequestasanattributethatthecontrollerand other elements in the process can use. It is bound by default under the key D i s p a t c h e r S e r v l e t . W E B _ A P P L I C A T I O N _ C O N T E X T _ A T T R I B U T E . 2. Thelocaleresolverisboundtotherequesttoenableelementsintheprocesstoresolvethelocaletouse whenprocessingtherequest (rendering the view, preparing data, and so on). If you do not need locale resolving,youdonotneedit. 3. Thethemeresolverisboundtotherequesttoletelementssuchasviewsdeterminewhichthemetouse.If youdonotusethemes,youcanignoreit. 4. If you specify a multipart file resolver, the request is inspected for multiparts if multiparts are found, the request is wrapped in a M u l t i p a r t H t t p S e r v l e t R e q u e s t for further processing by other elements in the process. (See Section 15.8.2, Using the MultipartResolver for further information about multipart handling). 5. An appropriate handler is searched for. If a handler is found, the execution chain associated with the handler (preprocessors, postprocessors, and controllers) is executed in order to prepare a model or rendering. 6. If a model is returned, the view is rendered. If no model is returned, (may be due to a preprocessor or postprocessorinterceptingthe request, perhaps for security reasons), no view is rendered, because the requestcouldalreadyhavebeenfulfilled. Handlerexceptionresolversthataredeclaredinthe W e b A p p l i c a t i o n C o n t e x t pickupexceptionsthatarethrown during processing of the request. Using these exception resolvers allows you to define custom behaviors to addressexceptions. TheSpring D i s p a t c h e r S e r v l e t alsosupportsthereturnofthe lastmodificationdate,asspecifiedbytheServlet API. The process of determining the last modification date for a specific request is straightforward: the D i s p a t c h e r S e r v l e t looks up an appropriate handler mapping and tests whether the handler that is found implementsthe L a s t M o d i f i e d interface. If so, the value of the l o n gg e t L a s t M o d i f i e d ( r e q u e s t ) method of the L a s t M o d i f i e d interfaceisreturnedtotheclient. You can customize individual D i s p a t c h e r S e r v l e t instances by adding servlet initialization parameters (i n i t p a r a m elements) to the servlet declaration in the w e b . x m l file. See the following table for the list of supported parameters.

Table15.2.D i s p a t c h e r S e r v l e t initializationparameters Explanation Classthatimplements W e b A p p l i c a t i o n C o n t e x t ,whichinstantiatesthecontext c o n t e x t C l a s s usedbythisservlet.Bydefault,theX m l W e b A p p l i c a t i o n C o n t e x t isused. Stringthatispassedtothecontextinstance(specifiedbyc o n t e x t C l a s s )to indicatewherecontext(s)canbefound.Thestringconsistspotentiallyof c o n t e x t C o n f i g L o c a t i o n multiplestrings(usingacommaasadelimiter)tosupportmultiplecontexts.In caseofmultiplecontextlocationswithbeansthataredefinedtwice,thelatest locationtakesprecedence. NamespaceoftheW e b A p p l i c a t i o n C o n t e x t .Defaultsto[ s e r v l e t n a m e ] n a m e s p a c e s e r v l e t . Parameter

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

5/30

2/3/2014

15. Web MVC framework

15.3ImplementingControllers
Controllers provide access to the application behavior that you typically define through a service interface. Controllersinterpretuserinputandtransformitintoamodelthatisrepresentedtotheuserbytheview.Spring implementsacontrollerinaveryabstractway,whichenablesyoutocreateawidevarietyofcontrollers. Spring2.5introducedanannotationbasedprogrammingmodelforMVCcontrollersthatusesannotationssuch as @ R e q u e s t M a p p i n g , @ R e q u e s t P a r a m , @ M o d e l A t t r i b u t e ,andsoon.Thisannotationsupportisavailableforboth ServletMVCandPortletMVC.Controllersimplementedinthisstyledonothavetoextendspecificbaseclasses orimplementspecificinterfaces.Furthermore,theydonotusuallyhavedirectdependenciesonServletorPortlet APIs,althoughyoucaneasilyconfigureaccesstoServletorPortletfacilities. Tip Availableinthesamplesrepository,the PetClinicwebapplicationleveragesthe annotation supportdescribedinthissection,inthecontextofsimpleformprocessing.
@ C o n t r o l l e r p u b l i cc l a s sH e l l o W o r l d C o n t r o l l e r{ @ R e q u e s t M a p p i n g ( " / h e l l o W o r l d " ) p u b l i cM o d e l A n d V i e wh e l l o W o r l d ( ){ M o d e l A n d V i e wm a v=n e wM o d e l A n d V i e w ( ) ; m a v . s e t V i e w N a m e ( " h e l l o W o r l d " ) ; m a v . a d d O b j e c t ( " m e s s a g e " ," H e l l oW o r l d ! " ) ; r e t u r nm a v ; }

Asyoucansee,the@ C o n t r o l l e r and@ R e q u e s t M a p p i n g annotationsallowflexiblemethodnamesandsignatures. In this particular example the method has no parameters and returns a M o d e l A n d V i e w , but various other (and better)strategiesexist,asareexplainedlaterinthissection. M o d e l A n d V i e w , @ C o n t r o l l e r ,and @ R e q u e s t M a p p i n g formthebasisfortheSpringMVCimplementation.Thissectiondocumentstheseannotationsandhowtheyare mostcommonlyusedinaServletenvironment.

15.3.1Definingacontrollerwith@ C o n t r o l l e r
The @ C o n t r o l l e r annotation indicates that a particular class serves the role of a controller. Spring does not requireyoutoextendanycontrollerbaseclassorreferencetheServletAPI.However,youcanstillreference Servletspecificfeaturesifyouneedto. The@ C o n t r o l l e r annotationactsasastereotypefortheannotatedclass,indicatingitsrole.Thedispatcherscans suchannotatedclassesformappedmethodsanddetects@ R e q u e s t M a p p i n g annotations(seethenextsection). Youcandefineannotatedcontrollerbeansexplicitly,usingastandardSpringbeandefinitioninthedispatcher's context.However,the@ C o n t r o l l e r stereotypealsoallowsforautodetection,alignedwithSpringgeneralsupport fordetectingcomponentclassesintheclasspathandautoregisteringbeandefinitionsforthem. Toenableautodetectionofsuchannotatedcontrollers,youaddcomponentscanningtoyourconfiguration.Use thespringcontextschemaasshowninthefollowingXMLsnippet:
< ? x m lv e r s i o n = " 1 . 0 "e n c o d i n g = " U T F 8 " ? > < b e a n sx m l n s = " h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / b e a n s " x m l n s : x s i = " h t t p : / / w w w . w 3 . o r g / 2 0 0 1 / X M L S c h e m a i n s t a n c e " x m l n s : p = " h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / p " x m l n s : c o n t e x t = " h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / c o n t e x t " x s i : s c h e m a L o c a t i o n = " h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / b e a n s h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / b e a n s / s p r i n g b e a n s 3 . 0 . x s d h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / c o n t e x t h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / c o n t e x t / s p r i n g c o n t e x t 3 . 0 . x s d " > < c o n t e x t : c o m p o n e n t s c a nb a s e p a c k a g e = " o r g . s p r i n g f r a m e w o r k . s a m p l e s . p e t c l i n i c . w e b " / > / /. . . < / b e a n s >

15.3.2Mappingrequestswith@ R e q u e s t M a p p i n g
Youusethe@ R e q u e s t M a p p i n g annotationtomapURLssuchas/ a p p o i n t m e n t s ontoanentireclassoraparticular handlermethod.Typicallytheclasslevelannotationmapsaspecificrequestpath(orpathpattern)ontoaform controller,withadditionalmethodlevelannotationsnarrowingtheprimarymappingforaspecificHTTPmethod requestmethod("GET"/"POST")orspecificHTTPrequestparameters. ThefollowingexampleshowsacontrollerinaSpringMVCapplicationthatusesthisannotation:
@ C o n t r o l l e r

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

6/30

2/3/2014
@ R e q u e s t M a p p i n g ( " / a p p o i n t m e n t s " ) p u b l i cc l a s sA p p o i n t m e n t s C o n t r o l l e r{

15. Web MVC framework

p r i v a t ef i n a lA p p o i n t m e n t B o o ka p p o i n t m e n t B o o k ; @ A u t o w i r e d p u b l i cA p p o i n t m e n t s C o n t r o l l e r ( A p p o i n t m e n t B o o ka p p o i n t m e n t B o o k ){ t h i s . a p p o i n t m e n t B o o k=a p p o i n t m e n t B o o k ; } @ R e q u e s t M a p p i n g ( m e t h o d=R e q u e s t M e t h o d . G E T ) p u b l i cM a p < S t r i n g ,A p p o i n t m e n t >g e t ( ){ r e t u r na p p o i n t m e n t B o o k . g e t A p p o i n t m e n t s F o r T o d a y ( ) ; } @ R e q u e s t M a p p i n g ( v a l u e = " / { d a y } " ,m e t h o d=R e q u e s t M e t h o d . G E T ) p u b l i cM a p < S t r i n g ,A p p o i n t m e n t >g e t F o r D a y ( @ P a t h V a r i a b l e@ D a t e T i m e F o r m a t ( i s o = I S O . D A T E )D a t ed a y ,M o d e lm o d e l ){ r e t u r na p p o i n t m e n t B o o k . g e t A p p o i n t m e n t s F o r D a y ( d a y ) ; } @ R e q u e s t M a p p i n g ( v a l u e = " / n e w " ,m e t h o d=R e q u e s t M e t h o d . G E T ) p u b l i cA p p o i n t m e n t F o r mg e t N e w F o r m ( ){ r e t u r nn e wA p p o i n t m e n t F o r m ( ) ; } @ R e q u e s t M a p p i n g ( m e t h o d=R e q u e s t M e t h o d . P O S T ) p u b l i cS t r i n ga d d ( @ V a l i dA p p o i n t m e n t F o r ma p p o i n t m e n t ,B i n d i n g R e s u l tr e s u l t ){ i f( r e s u l t . h a s E r r o r s ( ) ){ r e t u r n" a p p o i n t m e n t s / n e w " ; } a p p o i n t m e n t B o o k . a d d A p p o i n t m e n t ( a p p o i n t m e n t ) ; r e t u r n" r e d i r e c t : / a p p o i n t m e n t s " ; } }

Intheexample,the @ R e q u e s t M a p p i n g isusedinanumberofplaces.Thefirstusageisonthetype(class)level, which indicates that all handling methods on this controller are relativetothe / a p p o i n t m e n t s path. The g e t ( ) methodhasafurther@ R e q u e s t M a p p i n g refinement:itonlyacceptsGETrequests,meaningthatanHTTPGETfor / a p p o i n t m e n t s invokesthismethod.The p o s t ( ) hasasimilarrefinement,andthe g e t N e w F o r m ( ) combinesthe definitionofHTTPmethodandpathintoone,sothatGETrequestsfor a p p o i n t m e n t s / n e w arehandledbythat method. Theg e t F o r D a y ( ) methodshowsanotherusageof@ R e q u e s t M a p p i n g :URItemplates.(Seethenextsection). A @ R e q u e s t M a p p i n g ontheclasslevelisnotrequired.Withoutit,allpathsaresimplyabsolute,andnotrelative. The following example from the PetClinic sample application shows a multiaction controller using @ R e q u e s t M a p p i n g :
@ C o n t r o l l e r p u b l i cc l a s sC l i n i c C o n t r o l l e r{ p r i v a t ef i n a lC l i n i cc l i n i c ; @ A u t o w i r e d p u b l i cC l i n i c C o n t r o l l e r ( C l i n i cc l i n i c ){ t h i s . c l i n i c=c l i n i c ; } @ R e q u e s t M a p p i n g ( " / " ) p u b l i cv o i dw e l c o m e H a n d l e r ( ){ } @ R e q u e s t M a p p i n g ( " / v e t s " ) p u b l i cM o d e l M a pv e t s H a n d l e r ( ){ r e t u r nn e wM o d e l M a p ( t h i s . c l i n i c . g e t V e t s ( ) ) ; } }

Workingwithinterfacebased@Controllerclasses A common pitfall when working with annotated controller classes happens when applying functionalitythatrequirescreatingaproxyproxyforthecontrollerobject(e.g. @ T r a n s a c t i o n a l methods).UsuallyyouwillintroduceaninterfaceforthecontrollerinordertouseJDKdynamic proxies.Tomakethisworkyoumustmovethe @ R e q u e s t M a p p i n g annotationstotheinterface as as the mapping mechanism can only "see" the interface exposed by the proxy. As an alternative,youmaychoosetoactivatep r o x y t a r g e t c l a s s = " t r u e " intheconfigurationforthe functionality applied to the controller (in our transaction scenario in < t x : a n n o t a t i o n d r i v e n / > ). Doing so indicates that CGLIBbased subclass proxies should be used instead of interfacebased JDK proxies. For more information on various proxying mechanisms see Section7.6,Proxyingmechanisms. 15.3.2.1URITemplates ToaccesspartsofarequestURLinyourhandlingmethods,usetheURItemplatesinthe @ R e q u e s t M a p p i n g path value.
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 7/30

2/3/2014

15. Web MVC framework

Usethe @ P a t h V a r i a b l e methodparameterannotationtoindicate thatamethodparametershouldbeboundtothevalueofaURI templatevariable. The following code snippet shows the usage of a single @ P a t h V a r i a b l e inacontrollermethod:

URITemplates A URI Template is a URIlike string, containing one or more variable names. When you substitute values for these variables, the template becomes a URI. The proposed RFC for URI Templates defineshowaURIisparameterized.For example,theURITemplate
h t t p : / / w w w . e x a m p l e . c o m / u s e r s / { u s e r i d }

containsthevariable userid.Ifweassign the variable the value fred, the URI Templateyields:
h t t p : / / w w w . e x a m p l e . c o m / u s e r s / f r e d

During the processing of a request, the URI can be compared to an expected URI Template in order to extract a collectionofvariables.

@ R e q u e s t M a p p i n g ( v a l u e = " / o w n e r s / { o w n e r I d } " ,m e t h o d = R e q u e s t M e t h o d . G E T ) p u b l i cS t r i n gf i n d O w n e r ( @ P a t h V a r i a b l eS t r i n go w n e r I d ,M o d e lm o d e l ){ O w n e ro w n e r=o w n e r S e r v i c e . f i n d O w n e r ( o w n e r I d ) ; m o d e l . a d d A t t r i b u t e ( " o w n e r " ,o w n e r ) ; r e t u r n" d i s p l a y O w n e r " ; }

TheURITemplate"/ o w n e r s / { o w n e r I d } "specifiesthevariablename ownerId.Whenthecontrollerhandlesthis request,thevalueof ownerIdissettothevalueintherequestURI.Forexample,whenarequestcomesinfor /owners/fred,thevaluefredisboundtothemethodparameterS t r i n go w n e r I d . ThematchingofmethodparameternamestoURITemplatevariablenamescanonlybedoneifyourcodeis compiledwithdebuggingenabled.Ifyoudonothavedebuggingenabled,youmustspecifythenameoftheURI Template variable name in the @PathVariable annotation in order to bind the resolved value of the variable nametoamethodparameter.Forexample:
@ R e q u e s t M a p p i n g ( v a l u e = " / o w n e r s / { o w n e r I d } " ,m e t h o d = R e q u e s t M e t h o d . G E T ) p u b l i cS t r i n gf i n d O w n e r ( @ P a t h V a r i a b l e ( " o w n e r I d " )S t r i n go w n e r I d ,M o d e lm o d e l ){ / /i m p l e m e n t a t i o no m i t t e d }

Youcanalsouseacontrollermethodwiththefollowingsignature:
@ R e q u e s t M a p p i n g ( v a l u e = " / o w n e r s / { o w n e r I d } " ,m e t h o d = R e q u e s t M e t h o d . G E T ) p u b l i cS t r i n gf i n d O w n e r ( @ P a t h V a r i a b l e ( " o w n e r I d " )S t r i n gt h e O w n e r ,M o d e lm o d e l ){ / /i m p l e m e n t a t i o no m i t t e d }

Youcanusemultiple@PathVariableannotationstobindtomultipleURITemplatevariables:
@ R e q u e s t M a p p i n g ( v a l u e = " / o w n e r s / { o w n e r I d } / p e t s / { p e t I d } " ,m e t h o d = R e q u e s t M e t h o d . G E T ) p u b l i cS t r i n gf i n d P e t ( @ P a t h V a r i a b l eS t r i n go w n e r I d ,@ P a t h V a r i a b l eS t r i n gp e t I d ,M o d e lm o d e l ){ O w n e ro w n e r=o w n e r S e r v i c e . f i n d O w n e r ( o w n d e r I d ) ; P e tp e t=o w n e r . g e t P e t ( p e t I d ) ; m o d e l . a d d A t t r i b u t e ( " p e t " ,p e t ) ; r e t u r n" d i s p l a y P e t " ; }

Thefollowingcodesnippetshowstheusageofpathvariablesonarelativepath,sothatthe f i n d P e t ( ) method willbeinvokedfor/ o w n e r s / 4 2 / p e t s / 2 1 ,forinstance.


@ C o n t r o l l e r @ R e q u e s t M a p p i n g ( " / o w n e r s / { o w n e r I d } " ) p u b l i cc l a s sR e l a t i v e P a t h U r i T e m p l a t e C o n t r o l l e r{ @ R e q u e s t M a p p i n g ( " / p e t s / { p e t I d } " ) p u b l i cv o i df i n d P e t ( @ P a t h V a r i a b l eS t r i n go w n e r I d ,@ P a t h V a r i a b l eS t r i n gp e t I d ,M o d e lm o d e l ){ / /i m p l e m e n t a t i o no m i t t e d }

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

8/30

2/3/2014

15. Web MVC framework

Tip Method parameters that are decorated with the @ P a t h V a r i a b l e annotation can be of any simpletypesuchasint,long,Date,etc.Springautomaticallyconvertstotheappropriatetype andthrowsa T y p e M i s m a t c h E x c e p t i o n ifthetypeisnotcorrect.Youcanfurthercustomizethis conversion process by customizing the data binder. See Section 15.3.2.12, Customizing WebDataBinderinitialization. 15.3.2.2Advanced@ R e q u e s t M a p p i n g options InadditiontoURItemplates,the@ R e q u e s t M a p p i n g annotationalsosupportsAntstylepathpatterns(forexample, / m y P a t h / * . d o ). A combination of URI templates and Antstyle globs is also supported (for example, / o w n e r s / * / p e t s / { p e t I d } ). Thehandlermethodnamesaretakenintoaccountfornarrowingifnopathwasspecifiedexplicitly,accordingto the specified o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . m v c . m u l t i a c t i o n . M e t h o d N a m e R e s o l v e r (by default an o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . m v c . m u l t i a c t i o n . I n t e r n a l P a t h M e t h o d N a m e R e s o l v e r ). This only applies if annotationmappingsdonotspecifyapathmappingexplicitly.Inotherwords,themethodnameisonlyusedfor narrowingamongasetofmatchingmethodsitdoesnotconstituteaprimarypathmappingitself. If you have a single default method (without explicit path mapping), then all requests without a more specific mappedmethodfoundaredispatchedtoit.Ifyouhavemultiplesuchdefaultmethods,thenthemethodnameis takenintoaccountforchoosingbetweenthem. You can narrow path mappings through parameter conditions: a sequence of "myParam=myValue" style expressions,witharequestonlymappedifeachsuchparameterisfoundtohavethegivenvalue.Forexample:
@ C o n t r o l l e r @ R e q u e s t M a p p i n g ( " / o w n e r s / { o w n e r I d } " ) p u b l i cc l a s sR e l a t i v e P a t h U r i T e m p l a t e C o n t r o l l e r{ @ R e q u e s t M a p p i n g ( v a l u e=" / p e t s / { p e t I d } " ,p a r a m s = " m y P a r a m = m y V a l u e " ) p u b l i cv o i df i n d P e t ( @ P a t h V a r i a b l eS t r i n go w n e r I d ,@ P a t h V a r i a b l eS t r i n gp e t I d ,M o d e lm o d e l ){ / /i m p l e m e n t a t i o no m i t t e d }

"myParam" style expressions are also supported, with such parameters having to be present in the request (allowedtohaveanyvalue).Finally,"!myParam"styleexpressionsindicatethatthespecifiedparameteris not supposedtobepresentintherequest. Similarly,pathmappingscanbenarroweddownthroughheaderconditions:
@ C o n t r o l l e r @ R e q u e s t M a p p i n g ( " / o w n e r s / { o w n e r I d } " ) p u b l i cc l a s sR e l a t i v e P a t h U r i T e m p l a t e C o n t r o l l e r{ @ R e q u e s t M a p p i n g ( v a l u e=" / p e t s " ,m e t h o d=R e q u e s t M e t h o d . P O S T ,h e a d e r s = " c o n t e n t t y p e = t e x t / * " ) p u b l i cv o i da d d P e t ( P e tp e t ,@ P a t h V a r i a b l eS t r i n go w n e r I d ){ / /i m p l e m e n t a t i o no m i t t e d } }

Intheaboveexample,thea d d P e t ( ) methodisonlyinvokedwhenthec o n t e n t t y p e matchesthe t e x t / * pattern, forexample,t e x t / x m l . 15.3.2.3Supportedhandlermethodargumentsandreturntypes Handlermethodsthatareannotatedwith @ R e q u e s t M a p p i n g canhaveveryflexiblesignatures.Mostofthemcan beusedinarbitraryorder(seebelowformoredetails). Request or response objects (Servlet API). Choose any specific request or response type, for example S e r v l e t R e q u e s t orH t t p S e r v l e t R e q u e s t . Session object (Servlet API): of type H t t p S e s s i o n . An argument of this type enforces the presence of a correspondingsession.Asaconsequence,suchanargumentisnevern u l l . Note Sessionaccessmaynotbethreadsafe,inparticularinaServletenvironment.Consider settingthe A n n o t a t i o n M e t h o d H a n d l e r A d a p t e r 's"synchronizeOnSession"flagto"true"if multiplerequestsareallowedtoaccessasessionconcurrently.
o r g . s p r i n g f r a m e w o r k . w e b . c o n t e x t . r e q u e s t . W e b R e q u e s t o r g . s p r i n g f r a m e w o r k . w e b . c o n t e x t . r e q u e s t . N a t i v e W e b R e q u e s t .

or Allows for generic request parameter accessaswellasrequest/sessionattributeaccess,withouttiestothenativeServlet/PortletAPI.


http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 9/30

2/3/2014

15. Web MVC framework


j a v a . u t i l . L o c a l e forthecurrentrequestlocale,determinedbythemostspecificlocaleresolveravailable, ineffect,theconfiguredL o c a l e R e s o l v e r inaServletenvironment. j a v a . i o . I n p u t S t r e a m

/ j a v a . i o . R e a d e r for access to the request's content. This value is the raw InputStream/ReaderasexposedbytheServletAPI.
j a v a . i o . O u t p u t S t r e a m / j a v a . i o . W r i t e r for

generating the response's content. This value is the raw OutputStream/WriterasexposedbytheServletAPI.


j a v a . s e c u r i t y . P r i n c i p a l containingthecurrentlyauthenticateduser. @ P a t h V a r i a b l e annotated parameters for access to URI template variables. See Section 15.3.2.1, URI

Templates.
@ R e q u e s t P a r a m annotatedparametersforaccesstospecificServletrequestparameters.Parametervalues

areconvertedtothedeclaredmethodargumenttype.SeeSection15.3.2.4,Bindingrequestparametersto methodparameterswith@RequestParam.
@ R e q u e s t H e a d e r annotated parameters for access to specific Servlet request HTTP headers. Parameter

valuesareconvertedtothedeclaredmethodargumenttype.
@ R e q u e s t B o d y annotatedparametersforaccesstotheHTTPrequestbody.Parametervaluesareconverted tothedeclaredmethodargumenttypeusing H t t p M e s s a g e C o n v e r t e r s.SeeSection15.3.2.5,Mappingthe

requestbodywiththe@RequestBodyannotation.
H t t p E n t i t y < ? > parameters for access to the Servlet request HTTP headers and contents. The request stream will be converted to the entity body using H t t p M e s s a g e C o n v e r t e r s. See Section 15.3.2.7, Using

HttpEntity<?>.
j a v a . u t i l . M a p

/ o r g . s p r i n g f r a m e w o r k . u i . M o d e l / o r g . s p r i n g f r a m e w o r k . u i . M o d e l M a p for enriching the implicitmodelthatisexposedtothewebview. Command or form objects to bind parameters to: as bean properties or fields, with customizable type conversion, depending on @ I n i t B i n d e r methods and/or the HandlerAdapter configuration. See the w e b B i n d i n g I n i t i a l i z e r propertyon A n n o t a t i o n M e t h o d H a n d l e r A d a p t e r .Suchcommandobjectsalongwith their validation results will be exposed as model attributes by default, using the nonqualified command classnameinpropertynotation.Forexample,"orderAddress"fortype"mypackage.OrderAddress".Specify aparameterlevelM o d e l A t t r i b u t e annotationfordeclaringaspecificmodelattributename.
o r g . s p r i n g f r a m e w o r k . v a l i d a t i o n . E r r o r s

/ o r g . s p r i n g f r a m e w o r k . v a l i d a t i o n . B i n d i n g R e s u l t validation resultsforaprecedingcommandorformobject(theimmediatelyprecedingmethodargument).
o r g . s p r i n g f r a m e w o r k . w e b . b i n d . s u p p o r t . S e s s i o n S t a t u s

status handle for marking form processing as complete, which triggers the cleanup of session attributes that have been indicated by the @ S e s s i o n A t t r i b u t e s annotationatthehandlertypelevel. TheE r r o r s orB i n d i n g R e s u l t parametershavetofollowthemodelobjectthatisbeingboundimmediatelyasthe method signature might have more that one model object and Spring will create a separate B i n d i n g R e s u l t instanceforeachofthemsothefollowingsamplewon'twork: Example15.1.InvalidorderingofBindingResultand@ModelAttribute
@ R e q u e s t M a p p i n g ( m e t h o d=R e q u e s t M e t h o d . P O S T ) p u b l i cS t r i n gp r o c e s s S u b m i t ( @ M o d e l A t t r i b u t e ( " p e t " )P e tp e t , M o d e lm o d e l ,B i n d i n g R e s u l tr e s u l t ){}

Note,thatthereisaM o d e l parameterinbetweenP e t andB i n d i n g R e s u l t .Togetthisworkingyouhavetoreorder theparametersasfollows:


@ R e q u e s t M a p p i n g ( m e t h o d=R e q u e s t M e t h o d . P O S T ) p u b l i cS t r i n gp r o c e s s S u b m i t ( @ M o d e l A t t r i b u t e ( " p e t " )P e tp e t , B i n d i n g R e s u l tr e s u l t ,M o d e lm o d e l ){}

Thefollowingreturntypesaresupportedforhandlermethods: A M o d e l A n d V i e w object, with the model implicitly enriched with command objects and the results of @ M o d e l A t t r i b u t e annotatedreferencedataaccessormethods. AM o d e l object,withtheviewnameimplicitlydeterminedthrougha R e q u e s t T o V i e w N a m e T r a n s l a t o r andthe modelimplicitlyenrichedwithcommandobjectsandtheresultsof @ M o d e l A t t r i b u t e annotatedreference dataaccessormethods. A M a p object for exposing a model, with the view name implicitly determined through a
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 10/30

2/3/2014

15. Web MVC framework


R e q u e s t T o V i e w N a m e T r a n s l a t o r andthemodelimplicitlyenrichedwithcommandobjectsandtheresultsof @ M o d e l A t t r i b u t e annotatedreferencedataaccessormethods.

A V i e w object, with the model implicitly determined through command objects and @ M o d e l A t t r i b u t e annotatedreferencedataaccessor methods. The handler method may also programmatically enrich the modelbydeclaringaM o d e l argument(seeabove). A S t r i n g valuethatisinterpretedasthelogicalviewname,withthemodelimplicitlydeterminedthrough commandobjectsand @ M o d e l A t t r i b u t e annotatedreferencedataaccessormethods.Thehandlermethod mayalsoprogrammaticallyenrichthemodelbydeclaringaM o d e l argument(seeabove).
v o i d if the method handles the response itself (by writing the response content directly, declaring an argumentoftypeS e r v l e t R e s p o n s e /H t t p S e r v l e t R e s p o n s e forthatpurpose)oriftheviewnameissupposed tobeimplicitlydeterminedthroughaR e q u e s t T o V i e w N a m e T r a n s l a t o r (notdeclaringaresponseargumentin

thehandlermethodsignature). Ifthemethodisannotatedwith @ R e s p o n s e B o d y ,thereturntypeiswrittentotheresponseHTTPbody.The returnvaluewillbeconvertedtothedeclaredmethodargumenttypeusing H t t p M e s s a g e C o n v e r t e r s.See Section15.3.2.6,Mappingtheresponsebodywiththe@ResponseBodyannotation. AH t t p E n t i t y < ? > orR e s p o n s e E n t i t y < ? > objecttoprovideaccesstotheServletreponseHTTPheadersand contents. The entity body will be converted to the response stream using H t t p M e s s a g e C o n v e r t e r s. See Section15.3.2.7,UsingHttpEntity<?>. Any other return type is considered to be a single model attribute to be exposed to the view, using the attributenamespecifiedthrough @ M o d e l A t t r i b u t e atthemethodlevel(orthedefaultattributenamebased onthereturntypeclassname).Themodelisimplicitlyenrichedwithcommandobjectsandtheresultsof @ M o d e l A t t r i b u t e annotatedreferencedataaccessormethods. 15.3.2.4Bindingrequestparameterstomethodparameterswith@ R e q u e s t P a r a m Usethe@ R e q u e s t P a r a m annotationtobindrequestparameterstoamethodparameterinyourcontroller. Thefollowingcodesnippetshowstheusage:
@ C o n t r o l l e r @ R e q u e s t M a p p i n g ( " / p e t s " ) @ S e s s i o n A t t r i b u t e s ( " p e t " ) p u b l i cc l a s sE d i t P e t F o r m{ / /. . . @ R e q u e s t M a p p i n g ( m e t h o d=R e q u e s t M e t h o d . G E T ) p u b l i cS t r i n gs e t u p F o r m ( @ R e q u e s t P a r a m ( " p e t I d " )i n tp e t I d ,M o d e l M a pm o d e l ){ P e tp e t=t h i s . c l i n i c . l o a d P e t ( p e t I d ) ; m o d e l . a d d A t t r i b u t e ( " p e t " ,p e t ) ; r e t u r n" p e t F o r m " ; } / /. . .

Parameters using this annotation are required by default, but you can specify that a parameter is optional by setting@ R e q u e s t P a r a m 'sr e q u i r e d attributetof a l s e (e.g.,@ R e q u e s t P a r a m ( v a l u e = " i d " ,r e q u i r e d = f a l s e ) ). 15.3.2.5Mappingtherequestbodywiththe@RequestBodyannotation The@ R e q u e s t B o d y methodparameterannotationindicatesthatamethodparametershouldbeboundtothevalue oftheHTTPrequestbody.Forexample:
@ R e q u e s t M a p p i n g ( v a l u e=" / s o m e t h i n g " ,m e t h o d=R e q u e s t M e t h o d . P U T ) p u b l i cv o i dh a n d l e ( @ R e q u e s t B o d yS t r i n gb o d y ,W r i t e rw r i t e r )t h r o w sI O E x c e p t i o n{ w r i t e r . w r i t e ( b o d y ) ; }

YouconverttherequestbodytothemethodargumentbyusinganH t t p M e s s a g e C o n v e r t e r .H t t p M e s s a g e C o n v e r t e r isresponsibleforconvertingfromtheHTTPrequestmessagetoanobjectandconvertingfromanobjecttothe HTTP response body. D i s p a t c h e r S e r v l e t supports annotation based processing using the D e f a u l t A n n o t a t i o n H a n d l e r M a p p i n g and A n n o t a t i o n M e t h o d H a n d l e r A d a p t e r . In Spring 3.0 the A n n o t a t i o n M e t h o d H a n d l e r A d a p t e r is extended to support the @ R e q u e s t B o d y and has the following H t t p M e s s a g e C o n v e r t e r s registeredbydefault:
B y t e A r r a y H t t p M e s s a g e C o n v e r t e r convertsbytearrays. S t r i n g H t t p M e s s a g e C o n v e r t e r convertsstrings. F o r m H t t p M e s s a g e C o n v e r t e r convertsformdatato/fromaMultiValueMap<String,String>.

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

11/30

2/3/2014

15. Web MVC framework


S o u r c e H t t p M e s s a g e C o n v e r t e r convertsto/fromajavax.xml.transform.Source. M a r s h a l l i n g H t t p M e s s a g e C o n v e r t e r

converts to/from an object using the o r g . s p r i n g f r a m e w o r k . o x m

package. Formoreinformationontheseconverters,seeMessageConverters. The


M a r s h a l l i n g H t t p M e s s a g e C o n v e r t e r requires a M a r s h a l l e r and U n m a r s h a l l e r from the o r g . s p r i n g f r a m e w o r k . o x m packagetobeconfiguredonaninstanceof A n n o t a t i o n M e t h o d H a n d l e r A d a p t e r inthe

applicationcontext.Forexample:
< b e a nc l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . m v c . a n n o t a t i o n . A n n o t a t i o n M e t h o d H a n d l e r A d a p t e r " > < p r o p e r t yn a m e = " m e s s a g e C o n v e r t e r s " > < u t i l : l i s ti d = " b e a n L i s t " > < r e fb e a n = " s t r i n g H t t p M e s s a g e C o n v e r t e r " / > < r e fb e a n = " m a r s h a l l i n g H t t p M e s s a g e C o n v e r t e r " / > < / u t i l : l i s t > < / p r o p e r t y < / b e a n > < b e a ni d = " s t r i n g H t t p M e s s a g e C o n v e r t e r " c l a s s = " o r g . s p r i n g f r a m e w o r k . h t t p . c o n v e r t e r . S t r i n g H t t p M e s s a g e C o n v e r t e r " / > < b e a ni d = " m a r s h a l l i n g H t t p M e s s a g e C o n v e r t e r " c l a s s = " o r g . s p r i n g f r a m e w o r k . h t t p . c o n v e r t e r . x m l . M a r s h a l l i n g H t t p M e s s a g e C o n v e r t e r " > < p r o p e r t yn a m e = " m a r s h a l l e r "r e f = " c a s t o r M a r s h a l l e r "/ > < p r o p e r t yn a m e = " u n m a r s h a l l e r "r e f = " c a s t o r M a r s h a l l e r "/ > < / b e a n > < b e a ni d = " c a s t o r M a r s h a l l e r "c l a s s = " o r g . s p r i n g f r a m e w o r k . o x m . c a s t o r . C a s t o r M a r s h a l l e r " / >

15.3.2.6Mappingtheresponsebodywiththe@ R e s p o n s e B o d y annotation The@ R e s p o n s e B o d y annotationissimilarto@ R e q u e s t B o d y .Thisannotationcanbeputonamethodandindicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpretedasaviewname).Forexample:
@ R e q u e s t M a p p i n g ( v a l u e=" / s o m e t h i n g " ,m e t h o d=R e q u e s t M e t h o d . P U T ) @ R e s p o n s e B o d y p u b l i cS t r i n gh e l l o W o r l d ( ) { r e t u r n" H e l l oW o r l d " ; }

TheaboveexamplewillresultinthetextH e l l oW o r l d beingwrittentotheHTTPresponsestream. As with @ R e q u e s t B o d y , Spring converts the returned object to a response body by using an H t t p M e s s a g e C o n v e r t e r . For more information on these converters, see the previous section and Message Converters. 15.3.2.7UsingH t t p E n t i t y < ? > The H t t p E n t i t y is similar to @ R e q u e s t B o d y and @ R e s p o n s e B o d y . Besides getting access to the request and response body, H t t p E n t i t y (and the responsespecific subclass R e s p o n s e E n t i t y ) also allows access to the requestandresponseheaders,likeso:
@ R e q u e s t M a p p i n g ( " / s o m e t h i n g " ) p u b l i cR e s p o n s e E n t i t y < S t r i n g >h a n d l e ( H t t p E n t i t y < b y t e [ ] >r e q u e s t E n t i t y )t h r o w sU n s u p p o r t e d E n c o d i n g E x c e p t i o n{ S t r i n gr e q u e s t H e a d e r=r e q u e s t E n t i t y . g e t H e a d e r s ( ) . g e t F i r s t ( " M y R e q u e s t H e a d e r " ) ) ; b y t e [ ]r e q u e s t B o d y=r e q u e s t E n t i t y . g e t B o d y ( ) ; / /d os o m e t h i n gw i t hr e q u e s th e a d e ra n db o d y H t t p H e a d e r sr e s p o n s e H e a d e r s=n e wH t t p H e a d e r s ( ) ; r e s p o n s e H e a d e r s . s e t ( " M y R e s p o n s e H e a d e r " ," M y V a l u e " ) ; r e t u r nn e wR e s p o n s e E n t i t y < S t r i n g > ( " H e l l oW o r l d " ,r e s p o n s e H e a d e r s ,H t t p S t a t u s . C R E A T E D ) ;

The above example gets the value of the "MyRequestHeader" request header, and reads the body as a byte array.Itaddsthe"MyResponseHeader"totheresponse,writesH e l l oW o r l d totheresponsestream,andsetsthe responsestatuscodeto201(Created). Aswith@ R e q u e s t B o d y and@ R e s p o n s e B o d y ,SpringusesH t t p M e s s a g e C o n v e r t e r toconvertfromandtotherequest and response streams. For more information on these converters, see the previous section and Message Converters. 15.3.2.8Providingalinktodatafromthemodelwith@ M o d e l A t t r i b u t e
@ M o d e l A t t r i b u t e has two usage scenarios in controllers. When you place it on a method parameter, @ M o d e l A t t r i b u t e mapsamodelattributetothespecific,annotatedmethodparameter(seethe p r o c e s s S u b m i t ( )

methodbelow).Thisishowthecontrollergetsareferencetotheobjectholdingthedataenteredintheform.
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 12/30

2/3/2014

15. Web MVC framework

You can also use @ M o d e l A t t r i b u t e at the method level to provide reference data for the model (see the p o p u l a t e P e t T y p e s ( ) method in the following example). For this usage the method signature can contain the sametypesasdocumentedpreviouslyforthe@ R e q u e s t M a p p i n g annotation. Note
@ M o d e l A t t r i b u t e

annotated methods are executed before the chosen @ R e q u e s t M a p p i n g annotated handler method. They effectively prepopulate the implicit model with specific attributes, often loaded from a database. Such an attribute can then already be accessed through @ M o d e l A t t r i b u t e annotated handler method parameters in the chosen handler method,potentiallywithbindingandvalidationappliedtoit. Thefollowingcodesnippetshowsthesetwousagesofthisannotation:
@ C o n t r o l l e r @ R e q u e s t M a p p i n g ( " / o w n e r s / { o w n e r I d } / p e t s / { p e t I d } / e d i t " ) @ S e s s i o n A t t r i b u t e s ( " p e t " ) p u b l i cc l a s sE d i t P e t F o r m{ / /. . . @ M o d e l A t t r i b u t e ( " t y p e s " ) p u b l i cC o l l e c t i o n < P e t T y p e >p o p u l a t e P e t T y p e s ( ){ r e t u r nt h i s . c l i n i c . g e t P e t T y p e s ( ) ; } @ R e q u e s t M a p p i n g ( m e t h o d=R e q u e s t M e t h o d . P O S T ) p u b l i cS t r i n gp r o c e s s S u b m i t ( @ M o d e l A t t r i b u t e ( " p e t " )P e tp e t , B i n d i n g R e s u l tr e s u l t ,S e s s i o n S t a t u ss t a t u s ){ n e wP e t V a l i d a t o r ( ) . v a l i d a t e ( p e t ,r e s u l t ) ; i f( r e s u l t . h a s E r r o r s ( ) ){ r e t u r n" p e t F o r m " ; } e l s e{ t h i s . c l i n i c . s t o r e P e t ( p e t ) ; s t a t u s . s e t C o m p l e t e ( ) ; r e t u r n" r e d i r e c t : o w n e r . d o ? o w n e r I d = "+p e t . g e t O w n e r ( ) . g e t I d ( ) ; }

} }

15.3.2.9Specifyingattributestostoreinasessionwith@ S e s s i o n A t t r i b u t e s Thetypelevel @ S e s s i o n A t t r i b u t e s annotationdeclaressessionattributesusedbyaspecifichandler.Thiswill typicallylistthenamesofmodelattributesortypesofmodelattributeswhichshouldbetransparentlystoredinthe sessionorsomeconversationalstorage,servingasformbackingbeansbetweensubsequentrequests. Thefollowingcodesnippetshowstheusageofthisannotation,specifyingthemodelattributename:


@ C o n t r o l l e r @ R e q u e s t M a p p i n g ( " / e d i t P e t . d o " ) @ S e s s i o n A t t r i b u t e s ( " p e t " ) p u b l i cc l a s sE d i t P e t F o r m{ / /. . . }

Note When using controller interfaces (e.g. for AOP proxying), make sure to consistently put all your mapping annotations such as @ R e q u e s t M a p p i n g and @ S e s s i o n A t t r i b u t e s on the controllerinterfaceratherthanontheimplementationclass. 15.3.2.10Mappingcookievalueswiththe@CookieValueannotation The@ C o o k i e V a l u e annotationallowsamethodparametertobeboundtothevalueofanHTTPcookie. Letusconsiderthatthefollowingcookiehasbeenreceivedwithanhttprequest:
J S E S S I O N I D = 4 1 5 A 4 A C 1 7 8 C 5 9 D A C E 0 B 2 C 9 C A 7 2 7 C D D 8 4

ThefollowingcodesampledemonstrateshowtogetthevalueoftheJ S E S S I O N I D cookie:
@ R e q u e s t M a p p i n g ( " / d i s p l a y H e a d e r I n f o . d o " ) p u b l i cv o i dd i s p l a y H e a d e r I n f o ( @ C o o k i e V a l u e ( " J S E S S I O N I D " )S t r i n gc o o k i e ) { / / . . . }

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

13/30

2/3/2014

15. Web MVC framework

ThisannotationissupportedforannotatedhandlermethodsinServletandPortletenvironments. 15.3.2.11Mappingrequestheaderattributeswiththe@RequestHeaderannotation The@ R e q u e s t H e a d e r annotationallowsamethodparametertobeboundtoarequestheader. Hereisasamplerequestheader:


H o s t A c c e p t A c c e p t L a n g u a g e A c c e p t E n c o d i n g A c c e p t C h a r s e t K e e p A l i v e l o c a l h o s t : 8 0 8 0 t e x t / h t m l , a p p l i c a t i o n / x h t m l + x m l , a p p l i c a t i o n / x m l ; q = 0 . 9 f r , e n g b ; q = 0 . 7 , e n ; q = 0 . 3 g z i p , d e f l a t e I S O 8 8 5 9 1 , u t f 8 ; q = 0 . 7 , * ; q = 0 . 7 3 0 0

ThefollowingcodesampledemonstrateshowtogetthevalueoftheA c c e p t E n c o d i n g andK e e p A l i v e headers:


@ R e q u e s t M a p p i n g ( " / d i s p l a y H e a d e r I n f o . d o " ) p u b l i cv o i dd i s p l a y H e a d e r I n f o ( @ R e q u e s t H e a d e r ( " A c c e p t E n c o d i n g " )S t r i n ge n c o d i n g , @ R e q u e s t H e a d e r ( " K e e p A l i v e " )l o n gk e e p A l i v e ) { / / . . . }

ThisannotationissupportedforannotatedhandlermethodsinServletandPortletenvironments. 15.3.2.12CustomizingW e b D a t a B i n d e r initialization To customize request parameter binding with PropertyEditors through Spring's W e b D a t a B i n d e r , you can use either @ I n i t B i n d e r annotated methods within your controller or externalize your configuration by providing a customW e b B i n d i n g I n i t i a l i z e r .
Customizingdatabindingwith@ I n i t B i n d e r

Annotatingcontrollermethodswith @ I n i t B i n d e r allows you to configure web data binding directly within your controllerclass. @ I n i t B i n d e r identifies methods that initializethe W e b D a t a B i n d e r that will be used to populate commandandformobjectargumentsofannotatedhandlermethods. Suchinitbindermethodssupportallargumentsthat@ R e q u e s t M a p p i n g supports,exceptforcommand/formobjects and corresponding validation result objects. Initbinder methods must not have a return value. Thus, they are usually declared as v o i d . Typical arguments include W e b D a t a B i n d e r in combination with W e b R e q u e s t or j a v a . u t i l . L o c a l e ,allowingcodetoregistercontextspecificeditors. The following example demonstrates the use of @ I n i t B i n d e r to configure a C u s t o m D a t e E d i t o r for all j a v a . u t i l . D a t e formproperties.
@ C o n t r o l l e r p u b l i cc l a s sM y F o r m C o n t r o l l e r{ @ I n i t B i n d e r p u b l i cv o i di n i t B i n d e r ( W e b D a t a B i n d e rb i n d e r ){ S i m p l e D a t e F o r m a td a t e F o r m a t=n e wS i m p l e D a t e F o r m a t ( " y y y y M M d d " ) ; d a t e F o r m a t . s e t L e n i e n t ( f a l s e ) ; b i n d e r . r e g i s t e r C u s t o m E d i t o r ( D a t e . c l a s s ,n e wC u s t o m D a t e E d i t o r ( d a t e F o r m a t ,f a l s e ) ) ; } } / /. . .

ConfiguringacustomW e b B i n d i n g I n i t i a l i z e r

To externalize data binding initialization, you can provide a custom implementation of the W e b B i n d i n g I n i t i a l i z e r interface, which you then enable by supplying a custom bean configuration for an A n n o t a t i o n M e t h o d H a n d l e r A d a p t e r ,thusoverridingthedefaultconfiguration. ThefollowingexamplefromthePetClinicapplicationshowsaconfigurationusingacustomimplementationof the W e b B i n d i n g I n i t i a l i z e r interface, o r g . s p r i n g f r a m e w o r k . s a m p l e s . p e t c l i n i c . w e b . C l i n i c B i n d i n g I n i t i a l i z e r , which configures PropertyEditors requiredbyseveralofthePetCliniccontrollers.
< b e a nc l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . m v c . a n n o t a t i o n . A n n o t a t i o n M e t h o d H a n d l e r A d a p t e r " > < p r o p e r t yn a m e = " c a c h e S e c o n d s "v a l u e = " 0 "/ > < p r o p e r t yn a m e = " w e b B i n d i n g I n i t i a l i z e r " > < b e a nc l a s s = " o r g . s p r i n g f r a m e w o r k . s a m p l e s . p e t c l i n i c . w e b . C l i n i c B i n d i n g I n i t i a l i z e r "/ > < / p r o p e r t y > < / b e a n >

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

14/30

2/3/2014

15. Web MVC framework

15.4Handlermappings
InpreviousversionsofSpring,userswererequiredtodefine H a n d l e r M a p p i n g sinthewebapplicationcontextto mapincomingwebrequeststoappropriatehandlers.WiththeintroductionofSpring2.5,the D i s p a t c h e r S e r v l e t enablesthe D e f a u l t A n n o t a t i o n H a n d l e r M a p p i n g ,whichlooksfor @ R e q u e s t M a p p i n g annotationson @ C o n t r o l l e r s . Typically, you do not need to override this default mapping, unless you need to override the default property values.Thesepropertiesare:
i n t e r c e p t o r s

Listofinterceptorstouse. H a n d l e r I n t e r c e p t o r sarediscussedinSection15.4.1,Interceptingrequests theHandlerInterceptorinterface.


d e f a u l t H a n d l e r

Defaulthandlertouse,whenthishandlermappingdoesnotresultinamatchinghandler.
o r d e r

Based on the value of the order property (see the o r g . s p r i n g f r a m e w o r k . c o r e . O r d e r e d interface), Spring sortsallhandlermappingsavailableinthecontextandappliesthefirstmatchinghandler.
a l w a y s U s e F u l l P a t h

If t r u e ,Springusesthefullpathwithinthecurrentservletcontexttofindanappropriatehandler.If f a l s e (thedefault),thepathwithinthecurrentservletmappingisused.Forexample,ifaservletismappedusing / t e s t i n g / * andthea l w a y s U s e F u l l P a t h propertyissettotrue,/ t e s t i n g / v i e w P a g e . h t m l isused,whereasif thepropertyissettofalse,/ v i e w P a g e . h t m l isused.


u r l D e c o d e

Defaultstot r u e ,asofSpring2.5.Ifyouprefertocompareencodedpaths,setthisflagto f a l s e .However, the H t t p S e r v l e t R e q u e s t alwaysexposestheservletpathindecodedform.Beawarethattheservletpath willnotmatchwhencomparedwithencodedpaths.


l a z y I n i t H a n d l e r s

Allowslazyinitializationof singletonhandlers(prototypehandlersarealwayslazyinitialized).Thedefault valueisf a l s e . Note The a l w a y s U s e F u l l P a t h , u r l D e c o d e ,and l a z y I n i t H a n d l e r s properties are only available to subclassesofo r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . h a n d l e r . A b s t r a c t U r l H a n d l e r M a p p i n g . Thefollowingexampleshowshowtooverridethedefaultmappingandaddaninterceptor:
< b e a n s > < b e a ni d = " h a n d l e r M a p p i n g "c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . m v c . a n n o t a t i o n . D e f a u l t A n n o t a t i o n H a n d l e r M a p p i n g " < p r o p e r t yn a m e = " i n t e r c e p t o r s " > < b e a nc l a s s = " e x a m p l e . M y I n t e r c e p t o r " / > < / p r o p e r t y > < / b e a n > < b e a n s >

15.4.1InterceptingrequeststheH a n d l e r I n t e r c e p t o r interface
Spring'shandlermappingmechanismincludeshandlerinterceptors,whichareusefulwhenyouwanttoapply specificfunctionalitytocertainrequests,forexample,checkingforaprincipal. Interceptors located in the handler mapping must implement H a n d l e r I n t e r c e p t o r from o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t package. This interface defines three methods: one is called before the the actual handler is executed one is called after the handler is executed and one is called after the complete requesthasfinished.Thesethreemethodsshouldprovideenoughflexibilitytodoallkindsofpreprocessingand postprocessing. The p r e H a n d l e ( . . ) method returns a boolean value. You can use this method to break or continue the processingofthe execution chain. When this method returns t r u e ,the handler execution chain will continue whenitreturnsfalse,the D i s p a t c h e r S e r v l e t assumestheinterceptoritselfhastakencareofrequests(and,for example,renderedanappropriateview)anddoesnotcontinueexecutingtheotherinterceptorsandtheactual handlerintheexecutionchain. ThefollowingexampledefinesahandlermappingwhichmapsallrequestsmatchingtheURLpatterns"/*.form" and "/*.view" to a particular controller, e d i t A c c o u n t F o r m C o n t r o l l e r . An interceptor has been added that
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 15/30

2/3/2014

15. Web MVC framework

interceptstheserequestsandreroutestheusertoaspecificpageifthetimeisnotbetween9a.m.and6p.m.
< b e a n s > < b e a ni d = " h a n d l e r M a p p i n g " c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . h a n d l e r . S i m p l e U r l H a n d l e r M a p p i n g " > < p r o p e r t yn a m e = " i n t e r c e p t o r s " > < l i s t > < r e fb e a n = " o f f i c e H o u r s I n t e r c e p t o r " / > < / l i s t > < / p r o p e r t y > < p r o p e r t yn a m e = " m a p p i n g s " > < v a l u e > / * . f o r m = e d i t A c c o u n t F o r m C o n t r o l l e r / * . v i e w = e d i t A c c o u n t F o r m C o n t r o l l e r < / v a l u e > < / p r o p e r t y > < / b e a n > < b e a ni d = " o f f i c e H o u r s I n t e r c e p t o r " c l a s s = " s a m p l e s . T i m e B a s e d A c c e s s I n t e r c e p t o r " > < p r o p e r t yn a m e = " o p e n i n g T i m e "v a l u e = " 9 " / > < p r o p e r t yn a m e = " c l o s i n g T i m e "v a l u e = " 1 8 " / > < / b e a n > < b e a n s >

p a c k a g es a m p l e s ; p u b l i cc l a s sT i m e B a s e d A c c e s s I n t e r c e p t o re x t e n d sH a n d l e r I n t e r c e p t o r A d a p t e r{ p r i v a t ei n to p e n i n g T i m e ; p r i v a t ei n tc l o s i n g T i m e ; p u b l i cv o i ds e t O p e n i n g T i m e ( i n to p e n i n g T i m e ){ t h i s . o p e n i n g T i m e=o p e n i n g T i m e ; } p u b l i cv o i ds e t C l o s i n g T i m e ( i n tc l o s i n g T i m e ){ t h i s . c l o s i n g T i m e=c l o s i n g T i m e ; } p u b l i cb o o l e a np r e H a n d l e ( H t t p S e r v l e t R e q u e s tr e q u e s t , H t t p S e r v l e t R e s p o n s er e s p o n s e , O b j e c th a n d l e r )t h r o w sE x c e p t i o n{ C a l e n d a rc a l=C a l e n d a r . g e t I n s t a n c e ( ) ; i n th o u r=c a l . g e t ( H O U R _ O F _ D A Y ) ; i f( o p e n i n g T i m e< =h o u r<c l o s i n g T i m e ){ r e t u r nt r u e ; }e l s e{ r e s p o n s e . s e n d R e d i r e c t ( " h t t p : / / h o s t . c o m / o u t s i d e O f f i c e H o u r s . h t m l " ) ; r e t u r nf a l s e ; }

Anyrequesthandledbythismappingisinterceptedbythe T i m e B a s e d A c c e s s I n t e r c e p t o r .Ifthecurrenttimeis outsideofficehours,theuserisredirectedtoastaticHTMLfilethatsays,forexample,youcanonlyaccessthe websiteduringofficehours. As you can see, the Spring adapter class H a n d l e r I n t e r c e p t o r A d a p t e r makes it easier to extend the H a n d l e r I n t e r c e p t o r interface.

15.5Resolvingviews
AllMVCframeworksforwebapplicationsprovideawaytoaddressviews.Springprovidesviewresolvers,which enableyoutorendermodelsinabrowserwithouttyingyoutoaspecificviewtechnology.Outofthebox,Spring enablesyoutouseJSPs,VelocitytemplatesandXSLTviews,forexample.SeeChapter16, Viewtechnologies foradiscussionofhowtointegrateanduseanumberofdisparateviewtechnologies. The two interfaces that are important to the way Spring handles views are V i e w R e s o l v e r and V i e w . The V i e w R e s o l v e r provides a mapping between view names and actual views. The V i e w interface addresses the preparationoftherequestandhandstherequestovertooneoftheviewtechnologies.

15.5.1ResolvingviewswiththeV i e w R e s o l v e r interface
As discussed in Section 15.3, Implementing Controllers, all handler methods in the Spring Web MVC controllers must resolve to a logical view name, either explicitly (e.g., by returning a S t r i n g , V i e w , or M o d e l A n d V i e w )orimplicitly(i.e.,basedonconventions).ViewsinSpringareaddressedbyalogicalviewname andareresolvedbyaviewresolver.Springcomeswithquiteafewviewresolvers.Thistablelistsmostofthem acoupleofexamplesfollow.

Table15.3.Viewresolvers
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 16/30

2/3/2014
V i e w R e s o l v e r

15. Web MVC framework

Description Abstractviewresolverthatcachesviews.Oftenviewsneed A b s t r a c t C a c h i n g V i e w R e s o l v e r preparationbeforetheycanbeusedextendingthisviewresolver providescaching. ImplementationofV i e w R e s o l v e r thatacceptsaconfigurationfile X m l V i e w R e s o l v e r writteninXMLwiththesameDTDasSpring'sXMLbeanfactories. Thedefaultconfigurationfileis/ W E B I N F / v i e w s . x m l . ImplementationofV i e w R e s o l v e r thatusesbeandefinitionsina R e s o u r c e B u n d l e ,specifiedbythebundlebasename.Typicallyyou R e s o u r c e B u n d l e V i e w R e s o l v e r definethebundleinapropertiesfile,locatedintheclasspath.The defaultfilenameisv i e w s . p r o p e r t i e s . SimpleimplementationoftheV i e w R e s o l v e r interfacethateffectsthe directresolutionoflogicalviewnamestoURLs,withoutanexplicit U r l B a s e d V i e w R e s o l v e r mappingdefinition.Thisisappropriateifyourlogicalnamesmatch thenamesofyourviewresourcesinastraightforwardmanner, withouttheneedforarbitrarymappings. ConvenientsubclassofU r l B a s e d V i e w R e s o l v e r thatsupports I n t e r n a l R e s o u r c e V i e w (ineffect,ServletsandJSPs)and subclassessuchasJ s t l V i e w andT i l e s V i e w .Youcanspecifythe I n t e r n a l R e s o u r c e V i e w R e s o l v e r viewclassforallviewsgeneratedbythisresolverbyusing s e t V i e w C l a s s ( . . ) .SeetheJavadocsfortheU r l B a s e d V i e w R e s o l v e r classfordetails. ConvenientsubclassofU r l B a s e d V i e w R e s o l v e r thatsupports V e l o c i t y V i e w R e s o l v e r / V e l o c i t y V i e w (ineffect,Velocitytemplates)orF r e e M a r k e r V i e w F r e e M a r k e r V i e w R e s o l v e r ,respectively,andcustomsubclassesofthem. ImplementationoftheV i e w R e s o l v e r interfacethatresolvesaview C o n t e n t N e g o t i a t i n g V i e w R e s o l v e r basedontherequestfilenameorA c c e p t header.See Section15.5.4,ContentNegotiatingViewResolver.

As an example, with JSP as a view technology, you can use the U r l B a s e d V i e w R e s o l v e r . This view resolver translatesaviewnametoaURLandhandstherequestovertotheRequestDispatchertorendertheview.
< b e a ni d = " v i e w R e s o l v e r " c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . U r l B a s e d V i e w R e s o l v e r " > < p r o p e r t yn a m e = " v i e w C l a s s "v a l u e = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . J s t l V i e w " / > < p r o p e r t yn a m e = " p r e f i x "v a l u e = " / W E B I N F / j s p / " / > < p r o p e r t yn a m e = " s u f f i x "v a l u e = " . j s p " / > < / b e a n >

Whenreturning t e s t asalogicalviewname,thisviewresolverforwardstherequesttothe R e q u e s t D i s p a t c h e r thatwillsendtherequestto/ W E B I N F / j s p / t e s t . j s p . When you combine different view technologies in a web application, you can use the R e s o u r c e B u n d l e V i e w R e s o l v e r :
< b e a ni d = " v i e w R e s o l v e r " c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . R e s o u r c e B u n d l e V i e w R e s o l v e r " > < p r o p e r t yn a m e = " b a s e n a m e "v a l u e = " v i e w s " / > < p r o p e r t yn a m e = " d e f a u l t P a r e n t V i e w "v a l u e = " p a r e n t V i e w " / > < / b e a n >

TheR e s o u r c e B u n d l e V i e w R e s o l v e r inspectstheR e s o u r c e B u n d l e identifiedbythebasename,andforeachviewit issupposedtoresolve,itusesthevalueoftheproperty [ v i e w n a m e ] . ( c l a s s ) astheviewclassandthevalueof the property [ v i e w n a m e ] . u r l as the view url. Examples can be found in the next chapter which covers view technologies.Asyoucansee,youcanidentifyaparentview,fromwhichallviewsinthepropertiesfileextend. Thiswayyoucanspecifyadefaultviewclass,forexample. Note Subclasses of A b s t r a c t C a c h i n g V i e w R e s o l v e r cache view instances that they resolve. Cachingimprovesperformanceofcertainviewtechnologies.It'spossibletoturnoffthecache by setting the c a c h e property to f a l s e . Furthermore, if you must refresh a certain view at runtime (for example when a Velocity template is modified), you can use the r e m o v e F r o m C a c h e ( S t r i n gv i e w N a m e ,L o c a l el o c ) method.

15.5.2ChainingViewResolvers
Springsupportsmultipleviewresolvers.Thusyoucanchainresolversand,forexample,overridespecificviews incertaincircumstances.Youchainviewresolversbyaddingmorethanoneresolvertoyourapplicationcontext and,ifnecessary,bysettingtheo r d e r propertytospecifyordering.Remember,thehighertheorderproperty,the latertheviewresolverispositionedinthechain.
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 17/30

2/3/2014

15. Web MVC framework

In

example, the chain of view resolvers consists of two resolvers, an I n t e r n a l R e s o u r c e V i e w R e s o l v e r ,whichisalwaysautomaticallypositionedasthelastresolverinthechain,and an X m l V i e w R e s o l v e r for specifying Excel views. Excel views are not supported by the I n t e r n a l R e s o u r c e V i e w R e s o l v e r .
< b e a ni d = " j s p V i e w R e s o l v e r "c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . I n t e r n a l R e s o u r c e V i e w R e s o l v e r " > < p r o p e r t yn a m e = " v i e w C l a s s "v a l u e = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . J s t l V i e w " / > < p r o p e r t yn a m e = " p r e f i x "v a l u e = " / W E B I N F / j s p / " / > < p r o p e r t yn a m e = " s u f f i x "v a l u e = " . j s p " / > < / b e a n > < b e a ni d = " e x c e l V i e w R e s o l v e r "c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . X m l V i e w R e s o l v e r " > < p r o p e r t yn a m e = " o r d e r "v a l u e = " 1 " / > < p r o p e r t yn a m e = " l o c a t i o n "v a l u e = " / W E B I N F / v i e w s . x m l " / > < / b e a n > < ! -i nv i e w s . x m l> < b e a n s > < b e a nn a m e = " r e p o r t "c l a s s = " o r g . s p r i n g f r a m e w o r k . e x a m p l e . R e p o r t E x c e l V i e w " / > < / b e a n s >

the

following

If a specific view resolver does not result in a view, Spring examines the context for other view resolvers. If additional view resolvers exist, Spring continues to inspect them until a view is resolved. If no view resolver returnsaview,SpringthrowsaS e r v l e t E x c e p t i o n . Thecontractofaviewresolverspecifiesthataviewresolver canreturnnulltoindicatetheviewcouldnotbe found.Notallviewresolversdothis,however,becauseinsomecases,theresolversimplycannotdetectwhether ornottheviewexists.Forexample,the I n t e r n a l R e s o u r c e V i e w R e s o l v e r usesthe R e q u e s t D i s p a t c h e r internally, anddispatchingistheonlywaytofigureoutifaJSPexists,butthisactioncanonlyexecuteonce.Thesame holdsfortheV e l o c i t y V i e w R e s o l v e r andsomeothers.ChecktheJavadocfortheviewresolvertoseewhetherit reportsnonexistingviews.Thus,puttinganI n t e r n a l R e s o u r c e V i e w R e s o l v e r inthechaininaplaceotherthanthe last,resultsinthechainnotbeingfullyinspected,becausetheI n t e r n a l R e s o u r c e V i e w R e s o l v e r willalwaysreturn aview!

15.5.3Redirectingtoviews
Asmentionedpreviously,acontrollertypicallyreturnsalogicalviewname,whichaviewresolverresolvestoa particularviewtechnology.ForviewtechnologiessuchasJSPsthatareprocessedthroughtheServletorJSP engine, this resolution is usually handled through the combination of I n t e r n a l R e s o u r c e V i e w R e s o l v e r and I n t e r n a l R e s o u r c e V i e w , which issues an internal forward or include via the Servlet API's R e q u e s t D i s p a t c h e r . f o r w a r d ( . . ) methodorR e q u e s t D i s p a t c h e r . i n c l u d e ( ) method.Forotherviewtechnologies, suchasVelocity,XSLT,andsoon,theviewitselfwritesthecontentdirectlytotheresponsestream. It is sometimes desirable to issue an HTTP redirect back to the client, before the view is rendered. This is desirable,forexample,whenonecontrollerhasbeencalledwith P O S T eddata,andtheresponseisactuallya delegationtoanothercontroller(forexampleonasuccessfulformsubmission).Inthiscase,anormalinternal forwardwillmeanthattheothercontrollerwillalsoseethesame P O S T data,whichispotentiallyproblematicifit canconfuseitwithotherexpecteddata.Anotherreasontoperformaredirectbeforedisplayingtheresultisto eliminatethepossibilityoftheusersubmittingtheformdatamultipletimes.Inthisscenario,thebrowserwillfirst sendaninitial P O S T it will then receive a response to redirect to a different URL and finally the browser will performasubsequentG E T fortheURLnamedintheredirectresponse.Thus,fromtheperspectiveofthebrowser, thecurrentpagedoesnotreflecttheresultofaP O S T butratherofaG E T .Theendeffectisthatthereisnowaythe usercanaccidentallyreP O S T thesamedatabyperformingarefresh.TherefreshforcesaG E T oftheresultpage, notaresendoftheinitialP O S T data. 15.5.3.1R e d i r e c t V i e w One way to force a redirect as the result of a controller response is for the controller to create and return an instance of Spring's R e d i r e c t V i e w . In this case, D i s p a t c h e r S e r v l e t does not use the normal view resolution mechanism. Rather because it has been given the (redirect) view already, the D i s p a t c h e r S e r v l e t simply instructstheviewtodoitswork. The R e d i r e c t V i e w issuesan H t t p S e r v l e t R e s p o n s e . s e n d R e d i r e c t ( ) callthatreturnstotheclientbrowserasan HTTPredirect.AllmodelattributesareexposedasHTTPqueryparameters.Thismeansthatthemodelmust contain only objects (generally Strings or objects converted to a String representation), which can be readily convertedtoatextualHTTPqueryparameter. IfyouuseR e d i r e c t V i e w andtheviewiscreatedbythecontrolleritself,itisrecommendedthatyouconfigurethe redirect URL to be injected into the controller so that it is not baked into the controller but configured in the contextalongwiththeviewnames.Thenextsectiondiscussesthisprocess. 15.5.3.2Ther e d i r e c t : prefix WhiletheuseofR e d i r e c t V i e w worksfine,ifthecontrolleritselfcreatestheR e d i r e c t V i e w ,thereisnoavoidingthe factthatthecontrollerisawarethataredirectionishappening.Thisisreallysuboptimalandcouplesthingstoo
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 18/30

2/3/2014

15. Web MVC framework

tightly.Thecontrollershouldnotreallycareabouthowtheresponsegetshandled.Ingeneralitshouldoperate onlyintermsofviewnamesthathavebeeninjectedintoit. The special r e d i r e c t : prefix allows you to accomplish this. If a view name is returned that has the prefix r e d i r e c t : , the U r l B a s e d V i e w R e s o l v e r (and all subclasses) will recognize this as a special indication that a redirectisneeded.TherestoftheviewnamewillbetreatedastheredirectURL. TheneteffectisthesameasifthecontrollerhadreturnedaR e d i r e c t V i e w ,butnowthecontrolleritselfcansimply operateintermsoflogicalviewnames.Alogicalviewnamesuchas r e d i r e c t : / m y / r e s p o n s e / c o n t r o l l e r . h t m l will redirect relative to the current servlet context, while a name such as r e d i r e c t : h t t p : / / m y h o s t . c o m / s o m e / a r b i t r a r y / p a t h . h t m l willredirecttoanabsoluteURL.Theimportantthingis that, as long as this redirect view name is injected into the controller like any other logical view name, the controllerisnotevenawarethatredirectionishappening. 15.5.3.3Thef o r w a r d : prefix It is also possible to use a special f o r w a r d : prefix for view names that are ultimately resolved by U r l B a s e d V i e w R e s o l v e r and subclasses. This creates an I n t e r n a l R e s o u r c e V i e w (which ultimately does a R e q u e s t D i s p a t c h e r . f o r w a r d ( ) )around the rest of the view name, which is considered a URL. Therefore, this prefixisnotusefulwith I n t e r n a l R e s o u r c e V i e w R e s o l v e r and I n t e r n a l R e s o u r c e V i e w (forJSPsforexample).But theprefixcanbehelpfulwhenyouareprimarilyusinganotherviewtechnology,butstillwanttoforceaforwardof a resource to be handled by the Servlet/JSP engine. (Note that you may also chain multiple view resolvers, instead.) Aswithther e d i r e c t : prefix,iftheviewnamewiththef o r w a r d : prefixisinjectedintothecontroller,thecontroller doesnotdetectthatanythingspecialishappeningintermsofhandlingtheresponse.

15.5.4C o n t e n t N e g o t i a t i n g V i e w R e s o l v e r
TheC o n t e n t N e g o t i a t i n g V i e w R e s o l v e r doesnotresolveviewsitselfbutratherdelegatestootherviewresolvers, selectingtheviewthatresemblestherepresentationrequestedbytheclient.Twostrategiesexistforaclientto requestarepresentationfromtheserver: UseadistinctURIforeachresource,typicallybyusingadifferentfileextensionintheURI.Forexample, the URI h t t p : / / w w w . e x a m p l e . c o m / u s e r s / f r e d . p d f requests a PDF representation of the user fred, and h t t p : / / w w w . e x a m p l e . c o m / u s e r s / f r e d . x m l requestsanXMLrepresentation. UsethesameURIfortheclienttolocatetheresource,butsetthe A c c e p t HTTPrequestheadertolistthe mediatypesthatitunderstands.Forexample,anHTTPrequestfor h t t p : / / w w w . e x a m p l e . c o m / u s e r s / f r e d with an A c c e p t header set to a p p l i c a t i o n / p d f requests a PDF representation of the user fred, while h t t p : / / w w w . e x a m p l e . c o m / u s e r s / f r e d with an A c c e p t header set to t e x t / x m l requests an XML representation.Thisstrategyisknownascontentnegotiation. Note One issue with the A c c e p t header is that it is impossible to set it in a web browser within HTML.Forexample,inFirefox,itisfixedto:
A c c e p t :t e x t / h t m l , a p p l i c a t i o n / x h t m l + x m l , a p p l i c a t i o n / x m l ; q = 0 . 9 , * / * ; q = 0 . 8

ForthisreasonitiscommontoseetheuseofadistinctURIforeachrepresentationwhen developingbrowserbasedwebapplications. To support multiple representations of a resource, Spring provides the C o n t e n t N e g o t i a t i n g V i e w R e s o l v e r to resolve a view based on the file extension or A c c e p t header of the HTTP request. C o n t e n t N e g o t i a t i n g V i e w R e s o l v e r does not perform the view resolution itself but instead delegates to a list of viewresolversthatyouspecifythroughthebeanpropertyV i e w R e s o l v e r s . The C o n t e n t N e g o t i a t i n g V i e w R e s o l v e r selects an appropriate V i e w to handle the request by comparing the requestmediatype(s)withthemediatype(alsoknownasC o n t e n t T y p e )supportedbythe V i e w associatedwith eachofitsV i e w R e s o l v e r s .ThefirstV i e w inthelistthathasacompatibleC o n t e n t T y p e returnstherepresentation totheclient.Ifacompatibleviewcannotbesuppliedbythe V i e w R e s o l v e r chain,thenthelistofviewsspecified throughtheD e f a u l t V i e w s propertywillbeconsulted.ThislatteroptionisappropriateforsingletonV i e w s thatcan renderanappropriaterepresentation of the current resource regardless of the logical view name. The A c c e p t headermayincludewildcards,forexampletext/*,inwhichcasea V i e w whoseContentTypewastext/xmlisa compatiblematch. Tosupporttheresolutionofaviewbasedonafileextension,usethe C o n t e n t N e g o t i a t i n g V i e w R e s o l v e r bean propertym e d i a T y p e s tospecifyamappingoffileextensionstomediatypes.Formoreinformationonthealgorithm usedtodeterminetherequestmediatype,refertotheAPIdocumentationforC o n t e n t N e g o t i a t i n g V i e w R e s o l v e r . HereisanexampleconfigurationofaC o n t e n t N e g o t i a t i n g V i e w R e s o l v e r :
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 19/30

2/3/2014

15. Web MVC framework


< b e a nc l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . C o n t e n t N e g o t i a t i n g V i e w R e s o l v e r " > < p r o p e r t yn a m e = " m e d i a T y p e s " > < m a p > < e n t r yk e y = " a t o m "v a l u e = " a p p l i c a t i o n / a t o m + x m l " / > < e n t r yk e y = " h t m l "v a l u e = " t e x t / h t m l " / > < e n t r yk e y = " j s o n "v a l u e = " a p p l i c a t i o n / j s o n " / > < / m a p > < / p r o p e r t y > < p r o p e r t yn a m e = " v i e w R e s o l v e r s " > < l i s t > < b e a nc l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . B e a n N a m e V i e w R e s o l v e r " / > < b e a nc l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . I n t e r n a l R e s o u r c e V i e w R e s o l v e r " > < p r o p e r t yn a m e = " p r e f i x "v a l u e = " / W E B I N F / j s p / " / > < p r o p e r t yn a m e = " s u f f i x "v a l u e = " . j s p " / > < / b e a n > < / l i s t > < / p r o p e r t y > < p r o p e r t yn a m e = " d e f a u l t V i e w s " > < l i s t > < b e a nc l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . j s o n . M a p p i n g J a c k s o n J s o n V i e w "/ > < / l i s t > < / p r o p e r t y > < / b e a n > < b e a ni d = " c o n t e n t "c l a s s = " c o m . s p r i n g s o u r c e . s a m p l e s . r e s t . S a m p l e C o n t e n t A t o m V i e w " / >

The I n t e r n a l R e s o u r c e V i e w R e s o l v e r handles the translation of view names and JSP pages, while the B e a n N a m e V i e w R e s o l v e r returns a view based on the name of a bean. (See "Resolving views with the ViewResolverinterface"formoredetailsonhowSpringlooksupandinstantiatesaview.)Inthisexample,the c o n t e n t bean is a class that inherits from A b s t r a c t A t o m F e e d V i e w ,whichreturnsanAtomRSSfeed. For more informationoncreatinganAtomFeedrepresentation,seethesectionAtomViews. Intheaboveconfiguration,ifarequestismadewithan . h t m l extension,theviewresolverlooksforaviewthat matches the t e x t / h t m l media type. The I n t e r n a l R e s o u r c e V i e w R e s o l v e r provides the matching view for t e x t / h t m l .Iftherequestismadewiththefileextension. a t o m ,theviewresolverlooksforaviewthatmatchesthe a p p l i c a t i o n / a t o m + x m l media type. This view is provided by the B e a n N a m e V i e w R e s o l v e r that maps to the S a m p l e C o n t e n t A t o m V i e w iftheviewnamereturnedisc o n t e n t .Iftherequestismadewiththefileextension. j s o n , the M a p p i n g J a c k s o n J s o n V i e w instancefromthe D e f a u l t V i e w s listwillbeselectedregardlessoftheviewname. Alternatively,clientrequestscanbemadewithoutafileextensionbutwiththeA c c e p t headersettothepreferred mediatype,andthesameresolutionofrequesttoviewswouldoccur. Note If C o n t e n t N e g o t i a t i n g V i e w R e s o l v e r 's list of ViewResolvers is not configured explicitly, it automaticallyusesanyViewResolversdefinedintheapplicationcontext. The corresponding controller code that returns an Atom RSS feed for a URI of the form h t t p : / / l o c a l h o s t / c o n t e n t . a t o m orh t t p : / / l o c a l h o s t / c o n t e n t withanA c c e p t headerofapplication/atom+xmlis shownbelow.
@ C o n t r o l l e r p u b l i cc l a s sC o n t e n t C o n t r o l l e r{ p r i v a t eL i s t < S a m p l e C o n t e n t >c o n t e n t L i s t=n e wA r r a y L i s t < S a m p l e C o n t e n t > ( ) ; @ R e q u e s t M a p p i n g ( v a l u e = " / c o n t e n t " ,m e t h o d = R e q u e s t M e t h o d . G E T ) p u b l i cM o d e l A n d V i e wg e t C o n t e n t ( ){ M o d e l A n d V i e wm a v=n e wM o d e l A n d V i e w ( ) ; m a v . s e t V i e w N a m e ( " c o n t e n t " ) ; m a v . a d d O b j e c t ( " s a m p l e C o n t e n t L i s t " ,c o n t e n t L i s t ) ; r e t u r nm a v ; } }

15.6Usinglocales
Most parts of Spring's architecture support internationalization, just as the Spring web MVC framework does. D i s p a t c h e r S e r v l e t enablesyoutoautomaticallyresolvemessagesusingtheclient'slocale.Thisisdonewith L o c a l e R e s o l v e r objects. Whenarequestcomesin,theD i s p a t c h e r S e r v l e t looksforalocaleresolver,andifitfindsoneittriestouseitto set the locale. Using the R e q u e s t C o n t e x t . g e t L o c a l e ( ) method, you can always retrieve the locale that was resolvedbythelocaleresolver. In addition to automatic locale resolution, you can also attach an interceptor to the handler mapping (see Section15.4.1,InterceptingrequeststheHandlerInterceptorinterfaceformoreinformationonhandlermapping interceptors) to change the locale under specific circumstances, for example, based on a parameter in the request. Localeresolversandinterceptorsaredefinedinthe o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . i 1 8 n packageandare
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 20/30

2/3/2014

15. Web MVC framework

configuredinyourapplicationcontextinthenormalway.Hereisaselectionofthelocaleresolversincludedin Spring.

15.6.1A c c e p t H e a d e r L o c a l e R e s o l v e r
Thislocaleresolverinspectsthe a c c e p t l a n g u a g e headerintherequestthatwassentbytheclient(e.g.,aweb browser).Usuallythisheaderfieldcontainsthelocaleoftheclient'soperatingsystem.

15.6.2C o o k i e L o c a l e R e s o l v e r
ThislocaleresolverinspectsaC o o k i e thatmightexistontheclienttoseeifalocaleisspecified.Ifso,itusesthe specifiedlocale.Usingthepropertiesofthislocaleresolver,youcanspecifythenameofthecookieaswellas themaximumage.FindbelowanexampleofdefiningaC o o k i e L o c a l e R e s o l v e r .
< b e a ni d = " l o c a l e R e s o l v e r "c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . i 1 8 n . C o o k i e L o c a l e R e s o l v e r " > < p r o p e r t yn a m e = " c o o k i e N a m e "v a l u e = " c l i e n t l a n g u a g e " / > < ! -i ns e c o n d s .I fs e tt o1 ,t h ec o o k i ei sn o tp e r s i s t e d( d e l e t e dw h e nb r o w s e rs h u t sd o w n )> < p r o p e r t yn a m e = " c o o k i e M a x A g e "v a l u e = " 1 0 0 0 0 0 " > < / b e a n >

Table15.4.C o o k i e L o c a l e R e s o l v e r properties Property cookieName Default classname+ LOCALE Description Thenameofthecookie

Themaximumtimeacookiewillstaypersistentontheclient.If1is cookieMaxAge Integer.MAX_INT specified,thecookiewillnotbepersisteditwillonlybeavailable untiltheclientshutsdownhisorherbrowser. Limitsthevisibilityofthecookietoacertainpartofyoursite.When cookiePath / cookiePathisspecified,thecookiewillonlybevisibletothatpath andthepathsbelowit.

15.6.3S e s s i o n L o c a l e R e s o l v e r
The S e s s i o n L o c a l e R e s o l v e r allowsyoutoretrieve locales from the session that might be associated with the user'srequest.

15.6.4L o c a l e C h a n g e I n t e r c e p t o r
Youcanenablechangingoflocalesbyaddingthe L o c a l e C h a n g e I n t e r c e p t o r to one of the handler mappings (seeSection15.4,Handlermappings).Itwilldetectaparameterintherequestandchangethelocale.Itcalls s e t L o c a l e ( ) ontheL o c a l e R e s o l v e r thatalsoexistsinthecontext.Thefollowingexampleshowsthatcallstoall * . v i e w resourcescontainingaparameternamed s i t e L a n g u a g e willnowchangethelocale.So,forexample,a requestforthefollowingURL,h t t p : / / w w w . s f . n e t / h o m e . v i e w ? s i t e L a n g u a g e = n l willchangethesitelanguageto Dutch.
< b e a ni d = " l o c a l e C h a n g e I n t e r c e p t o r " c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . i 1 8 n . L o c a l e C h a n g e I n t e r c e p t o r " > < p r o p e r t yn a m e = " p a r a m N a m e "v a l u e = " s i t e L a n g u a g e " / > < / b e a n > < b e a ni d = " l o c a l e R e s o l v e r " c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . i 1 8 n . C o o k i e L o c a l e R e s o l v e r " / > < b e a ni d = " u r l M a p p i n g " c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . h a n d l e r . S i m p l e U r l H a n d l e r M a p p i n g " > < p r o p e r t yn a m e = " i n t e r c e p t o r s " > < l i s t > < r e fb e a n = " l o c a l e C h a n g e I n t e r c e p t o r " / > < / l i s t > < / p r o p e r t y > < p r o p e r t yn a m e = " m a p p i n g s " > < v a l u e > / * * / * . v i e w = s o m e C o n t r o l l e r < / v a l u e > < / p r o p e r t y > < / b e a n >

15.7Usingthemes
15.7.1Overviewofthemes
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 21/30

2/3/2014

15. Web MVC framework

YoucanapplySpringWebMVCframeworkthemestosettheoveralllookandfeelofyourapplication,thereby enhancinguserexperience.Athemeisacollectionofstaticresources,typicallystylesheetsandimages,that affectthevisualstyleoftheapplication.

15.7.2Definingthemes
To use themes in your web application, you must set up an implementation of the o r g . s p r i n g f r a m e w o r k . u i . c o n t e x t . T h e m e S o u r c e interface. The W e b A p p l i c a t i o n C o n t e x t interface extends T h e m e S o u r c e butdelegatesitsresponsibilitiestoadedicatedimplementation.Bydefaultthedelegatewillbean o r g . s p r i n g f r a m e w o r k . u i . c o n t e x t . s u p p o r t . R e s o u r c e B u n d l e T h e m e S o u r c e implementation that loads properties filesfromtherootoftheclasspath.TouseacustomT h e m e S o u r c e implementationortoconfigurethebasename prefixofthe R e s o u r c e B u n d l e T h e m e S o u r c e ,youcanregisterabean in the application context with the reserved namet h e m e S o u r c e .Thewebapplicationcontextautomaticallydetectsabeanwiththatnameandusesit. Whenusingthe R e s o u r c e B u n d l e T h e m e S o u r c e ,athemeisdefinedinasimplepropertiesfile.Thepropertiesfile liststheresourcesthatmakeupthetheme.Hereisanexample:
s t y l e S h e e t = / t h e m e s / c o o l / s t y l e . c s s b a c k g r o u n d = / t h e m e s / c o o l / i m g / c o o l B g . j p g

The keys of the properties are the names that refer to the themed elements from view code. For a JSP, you typically do this using the s p r i n g : t h e m e custom tag, which is very similar to the s p r i n g : m e s s a g e tag. The followingJSPfragmentusesthethemedefinedinthepreviousexampletocustomizethelookandfeel:
< % @t a g l i bp r e f i x = " s p r i n g "u r i = " h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / t a g s " % > < h t m l > < h e a d > < l i n kr e l = " s t y l e s h e e t "h r e f = " < s p r i n g : t h e m ec o d e = ' s t y l e S h e e t ' / > "t y p e = " t e x t / c s s " / > < / h e a d > < b o d ys t y l e = " b a c k g r o u n d = < s p r i n g : t h e m ec o d e = ' b a c k g r o u n d ' / > " > . . . < / b o d y > < / h t m l >

Bydefault,theR e s o u r c e B u n d l e T h e m e S o u r c e usesanemptybasenameprefix.Asaresult,thepropertiesfilesare loadedfromtherootoftheclasspath.Thusyouwouldputthec o o l . p r o p e r t i e s themedefinitioninadirectoryat therootoftheclasspath,forexample,in / W E B I N F / c l a s s e s .The R e s o u r c e B u n d l e T h e m e S o u r c e usesthestandard Javaresourcebundleloadingmechanism,allowingforfullinternationalizationofthemes.Forexample,wecould havea/ W E B I N F / c l a s s e s / c o o l _ n l . p r o p e r t i e s thatreferencesaspecialbackgroundimagewithDutchtextonit.

15.7.3Themeresolvers
Afteryoudefinethemes,asintheprecedingsection,youdecidewhichthemetouse.TheD i s p a t c h e r S e r v l e t will lookforabeannamedt h e m e R e s o l v e r tofindoutwhich T h e m e R e s o l v e r implementationtouse.Athemeresolver worksinmuchthesamewayasa L o c a l e R e s o l v e r .Itdetectsthethemetouseforaparticularrequestandcan alsoaltertherequest'stheme.ThefollowingthemeresolversareprovidedbySpring:

Table15.5.T h e m e R e s o l v e r implementations Description Selectsafixedtheme,setusingthed e f a u l t T h e m e N a m e property. Thethemeismaintainedintheuser'sHTTPsession.Itonlyneedstobeset S e s s i o n T h e m e R e s o l v e r onceforeachsession,butisnotpersistedbetweensessions. C o o k i e T h e m e R e s o l v e r Theselectedthemeisstoredinacookieontheclient.


F i x e d T h e m e R e s o l v e r

Class

Spring also provides a T h e m e C h a n g e I n t e r c e p t o r that allows theme changes on every request with a simple requestparameter.

15.8Spring'smultipart(fileupload)support
15.8.1Introduction
Spring'sbuiltinmultipartsupporthandlesfileuploadsinwebapplications.Youenablethismultipartsupportwith pluggable M u l t i p a r t R e s o l v e r objects, defined in the o r g . s p r i n g f r a m e w o r k . w e b . m u l t i p a r t package. Spring providesaM u l t i p a r t R e s o l v e r forusewithCommonsFileUpload). Bydefault,Springdoesnomultiparthandling,becausesomedeveloperswanttohandlemultipartsthemselves. You enable Spring multipart handling by adding a multipart resolver to the web application's context. Each
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 22/30

2/3/2014

15. Web MVC framework

requestisinspectedtoseeifitcontainsamultipart.Ifnomultipartisfound,therequestcontinuesasexpected.If amultipartisfoundintherequest,the M u l t i p a r t R e s o l v e r thathasbeendeclaredinyourcontextisused.After that,themultipartattributeinyourrequestistreatedlikeanyotherattribute.

15.8.2UsingtheM u l t i p a r t R e s o l v e r
ThefollowingexampleshowshowtousetheC o m m o n s M u l t i p a r t R e s o l v e r :
< b e a ni d = " m u l t i p a r t R e s o l v e r " c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . m u l t i p a r t . c o m m o n s . C o m m o n s M u l t i p a r t R e s o l v e r " > < ! -o n eo ft h ep r o p e r t i e sa v a i l a b l e ;t h em a x i m u mf i l es i z ei nb y t e s> < p r o p e r t yn a m e = " m a x U p l o a d S i z e "v a l u e = " 1 0 0 0 0 0 " / > < / b e a n >

Ofcourseyoualsoneedtoputtheappropriatejarsinyourclasspathforthemultipartresolvertowork.Inthecase oftheC o m m o n s M u l t i p a r t R e s o l v e r ,youneedtousec o m m o n s f i l e u p l o a d . j a r . WhentheSpringD i s p a t c h e r S e r v l e t detectsamultipartrequest,itactivatestheresolverthathasbeendeclared inyour context and hands over the request. The resolver then wraps the current H t t p S e r v l e t R e q u e s t into a M u l t i p a r t H t t p S e r v l e t R e q u e s t thatsupportsmultipartfileuploads.UsingtheM u l t i p a r t H t t p S e r v l e t R e q u e s t ,you cangetinformationaboutthemultipartscontainedbythisrequestandactuallygetaccesstothemultipartfiles themselvesinyourcontrollers.

15.8.3Handlingafileuploadinaform
AftertheM u l t i p a r t R e s o l v e r completesitsjob,therequestisprocessedlikeanyother.First,createaformwitha fileinputthatwillallowtheusertouploadaform.Theencodingattribute(e n c t y p e = " m u l t i p a r t / f o r m d a t a " )lets thebrowserknowhowtoencodetheformasmultipartrequest:
< h t m l > < h e a d > < t i t l e > U p l o a daf i l ep l e a s e < / t i t l e > < / h e a d > < b o d y > < h 1 > P l e a s eu p l o a daf i l e < / h 1 > < f o r mm e t h o d = " p o s t "a c t i o n = " / f o r m "e n c t y p e = " m u l t i p a r t / f o r m d a t a " > < i n p u tt y p e = " t e x t "n a m e = " n a m e " / > < i n p u tt y p e = " f i l e "n a m e = " f i l e " / > < i n p u tt y p e = " s u b m i t " / > < / f o r m > < / b o d y > < / h t m l >

The next step is to create a controller that handles the file upload. This controller is very similar to a normal annotated @ C o n t r o l l e r , except that we use M u l t i p a r t H t t p S e r v l e t R e q u e s t or M u l t i p a r t F i l e in the method parameters:
@ C o n t r o l l e r p u b l i cc l a s sF i l e U p o a d C o n t r o l l e r{ @ R e q u e s t M a p p i n g ( v a l u e=" / f o r m " ,m e t h o d=R e q u e s t M e t h o d . P O S T ) p u b l i cS t r i n gh a n d l e F o r m U p l o a d ( @ R e q u e s t P a r a m ( " n a m e " )S t r i n gn a m e , @ R e q u e s t P a r a m ( " f i l e " )M u l t i p a r t F i l ef i l e ){ i f( ! f i l e . i s E m p t y ( ) ){ b y t e [ ]b y t e s=f i l e . g e t B y t e s ( ) ; / /s t o r et h eb y t e ss o m e w h e r e r e t u r n" r e d i r e c t : u p l o a d S u c c e s s " ; }e l s e{ r e t u r n" r e d i r e c t : u p l o a d F a i l u r e " ; }

} }

Notehowthe@ R e q u e s t P a r a m methodparametersmaptotheinputelementsdeclaredintheform.Inthisexample, nothingisdonewiththeb y t e [ ] ,butinpracticeyoucansaveitinadatabase,storeitonthefilesystem,andso on. Finally,youwillhavetodeclarethecontrollerandtheresolverintheapplicationcontext:


< b e a n s > < b e a ni d = " m u l t i p a r t R e s o l v e r " c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . m u l t i p a r t . c o m m o n s . C o m m o n s M u l t i p a r t R e s o l v e r " / > < ! -D e c l a r ee x p l i c i t l y ,o ru s e< c o n t e x t : a n n o t a t i o n c o n f i g / >> < b e a ni d = " f i l e U p l o a d C o n t r o l l e r "c l a s s = " e x a m p l e s . F i l e U p l o a d C o n t r o l l e r " / > < / b e a n s >

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

23/30

2/3/2014

15. Web MVC framework

15.9Handlingexceptions
15.9.1H a n d l e r E x c e p t i o n R e s o l v e r
Spring H a n d l e r E x c e p t i o n R e s o l v e r s ease the pain of unexpected exceptions that occur while your request is handledbyacontrollerthatmatchedtherequest.H a n d l e r E x c e p t i o n R e s o l v e r s somewhatresembletheexception mappingsyoucandefineinthewebapplicationdescriptorw e b . x m l .However,theyprovideamoreflexiblewayto handle exceptions. They provide information about which handler was executing when the exception was thrown. Furthermore, a programmatic way of handling exceptions gives you more options for responding appropriatelybeforetherequestisforwardedtoanotherURL(thesameendresultaswhenyouusetheservlet specificexceptionmappings). Besides implementing the H a n d l e r E x c e p t i o n R e s o l v e r interface, which is only a matter of implementing the r e s o l v e E x c e p t i o n ( E x c e p t i o n , H a n d l e r ) method and returning a M o d e l A n d V i e w , you may also use the S i m p l e M a p p i n g E x c e p t i o n R e s o l v e r .Thisresolverenablesyoutotaketheclassnameofanyexceptionthatmight bethrownandmapittoaviewname.Thisisfunctionallyequivalenttotheexceptionmappingfeaturefromthe Servlet API, but it is also possible to implement more finely grained mappings of exceptions from different handlers. By default, the D i s p a t c h e r S e r v l e t registers the D e f a u l t H a n d l e r E x c e p t i o n R e s o l v e r . This resolver handles certainstandardSpringMVCexceptionsbysettingaspecificresponsestatuscode: HTTPStatusCode 500(InternalServerError) H t t p M e d i a T y p e N o t A c c e p t a b l e E x c e p t i o n 406(NotAcceptable) H t t p M e d i a T y p e N o t S u p p o r t e d E x c e p t i o n 415(UnsupportedMediaType) H t t p M e s s a g e N o t R e a d a b l e E x c e p t i o n 400(BadRequest) H t t p M e s s a g e N o t W r i t a b l e E x c e p t i o n 500(InternalServerError) H t t p R e q u e s t M e t h o d N o t S u p p o r t e d E x c e p t i o n 405(MethodNotAllowed) M i s s i n g S e r v l e t R e q u e s t P a r a m e t e r E x c e p t i o n400(BadRequest) N o S u c h R e q u e s t H a n d l i n g M e t h o d E x c e p t i o n 404(NotFound) T y p e M i s m a t c h E x c e p t i o n 400(BadRequest)
C o n v e r s i o n N o t S u p p o r t e d E x c e p t i o n

Exception

15.9.2@ E x c e p t i o n H a n d l e r
An alternative to the H a n d l e r E x c e p t i o n R e s o l v e r interface is the @ E x c e p t i o n H a n d l e r annotation. You use the @ E x c e p t i o n H a n d l e r methodannotationwithinacontrollertospecifywhichmethodisinvokedwhenanexception ofaspecifictypeisthrownduringtheexecutionofcontrollermethods.Forexample:
@ C o n t r o l l e r p u b l i cc l a s sS i m p l e C o n t r o l l e r{ / /o t h e rc o n t r o l l e rm e t h o do m i t t e d @ E x c e p t i o n H a n d l e r ( I O E x c e p t i o n . c l a s s ) p u b l i cS t r i n gh a n d l e I O E x c e p t i o n ( I O E x c e p t i o ne x ,H t t p S e r v l e t R e q u e s tr e q u e s t ){ r e t u r nC l a s s U t i l s . g e t S h o r t N a m e ( e x . g e t C l a s s ( ) ) ; }

willinvokethe'handlerIOException'methodwhenaj a v a . i o . I O E x c e p t i o n isthrown. The@ E x c e p t i o n H a n d l e r valuecanbesettoanarrayofExceptiontypes.Ifanexceptionisthrownmatchesoneof the types in the list, then the method annotated with the matching @ E x c e p t i o n H a n d l e r will be invoked. If the annotationvalueisnotsetthentheexceptiontypeslistedasmethodargumentsareused. Muchlikestandardcontrollermethodsannotatedwitha@ R e q u e s t M a p p i n g annotation,themethodargumentsand return values of @ E x c e p t i o n H a n d l e r methods are very flexible. For example, the H t t p S e r v l e t R e q u e s t can be accessed in Servlet environments and the P o r t l e t R e q u e s t in Portlet environments. The return type can be a S t r i n g ,whichisinterpretedasaviewnameora M o d e l A n d V i e w object.RefertotheAPIdocumentationformore details.

15.10Conventionoverconfigurationsupport
Foralotofprojects,stickingtoestablishedconventionsandhavingreasonabledefaultsisjustwhatthey(the projects)need...thisthemeofconventionoverconfigurationnowhasexplicitsupportinSpringWebMVC.What thismeansisthatifyouestablishasetofnamingconventionsandsuchlike,youcan substantiallycutdownon theamountofconfigurationthatisrequiredtosetuphandlermappings,viewresolvers,M o d e l A n d V i e w instances, etc.Thisisagreatboonwithregardstorapidprototyping,andcanalsolendadegreeof(alwaysgoodtohave) consistencyacrossacodebaseshouldyouchoosetomoveforwardwithitintoproduction.

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

24/30

2/3/2014

15. Web MVC framework

ConventionoverconfigurationsupportaddressesthethreecoreareasofMVCmodels,views,andcontrollers.

15.10.1TheControllerC o n t r o l l e r C l a s s N a m e H a n d l e r M a p p i n g
The C o n t r o l l e r C l a s s N a m e H a n d l e r M a p p i n g classisa H a n d l e r M a p p i n g implementationthatusesaconventionto determinethemappingbetweenrequestURLsandtheC o n t r o l l e r instancesthataretohandlethoserequests. ConsiderthefollowingsimpleC o n t r o l l e r implementation.Takespecialnoticeofthenameoftheclass.
p u b l i cc l a s sV i e w S h o p p i n g C a r t C o n t r o l l e ri m p l e m e n t sC o n t r o l l e r{ p u b l i cM o d e l A n d V i e wh a n d l e R e q u e s t ( H t t p S e r v l e t R e q u e s tr e q u e s t ,H t t p S e r v l e t R e s p o n s er e s p o n s e ){ / /t h ei m p l e m e n t a t i o ni sn o th u g e l yi m p o r t a n tf o rt h i se x a m p l e . . . }

HereisasnippetfromtheattendentSpringWebMVCconfigurationfile...
< b e a nc l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . m v c . s u p p o r t . C o n t r o l l e r C l a s s N a m e H a n d l e r M a p p i n g " / > < b e a ni d = " v i e w S h o p p i n g C a r t "c l a s s = " x . y . z . V i e w S h o p p i n g C a r t C o n t r o l l e r " > < ! -i n j e c td e p e n d e n c i e sa sr e q u i r e d . . .> < / b e a n >

The C o n t r o l l e r C l a s s N a m e H a n d l e r M a p p i n g findsall of the various handler (or C o n t r o l l e r ) beans defined in its application context and strips C o n t r o l l e r off the name to define its handler mappings. Thus, V i e w S h o p p i n g C a r t C o n t r o l l e r mapstothe/ v i e w s h o p p i n g c a r t * requestURL. Let'slookatsomemoreexamplessothatthecentralideabecomesimmediatelyfamiliar.(Noticealllowercasein theURLs,incontrasttocamelcasedC o n t r o l l e r classnames.)
W e l c o m e C o n t r o l l e r mapstothe/ w e l c o m e * requestURL H o m e C o n t r o l l e r mapstothe/ h o m e * requestURL I n d e x C o n t r o l l e r mapstothe/ i n d e x * requestURL R e g i s t e r C o n t r o l l e r mapstothe/ r e g i s t e r * requestURL

InthecaseofM u l t i A c t i o n C o n t r o l l e r handlerclasses,themappingsgeneratedareslightlymorecomplex.The C o n t r o l l e r namesinthefollowingexamplesareassumedtobeM u l t i A c t i o n C o n t r o l l e r implementations:


A d m i n C o n t r o l l e r mapstothe/ a d m i n /*requestURL C a t a l o g C o n t r o l l e r mapstothe/ c a t a l o g /*requestURL

If you follow the convention of naming your C o n t r o l l e r implementations as x x x Controller, the C o n t r o l l e r C l a s s N a m e H a n d l e r M a p p i n g savesyouthetediumofdefiningandmaintainingapotentially looooong S i m p l e U r l H a n d l e r M a p p i n g (orsuchlike). The C o n t r o l l e r C l a s s N a m e H a n d l e r M a p p i n g class extends the A b s t r a c t H a n d l e r M a p p i n g base class so you can define H a n d l e r I n t e r c e p t o r instances and everything else just as you would with many other H a n d l e r M a p p i n g implementations.

15.10.2TheModelM o d e l M a p (M o d e l A n d V i e w )
TheM o d e l M a p classisessentiallyaglorifiedM a p thatcanmakeaddingobjectsthataretobedisplayedin(oron)a V i e w adhere to a common naming convention. Consider the following C o n t r o l l e r implementation notice that objectsareaddedtotheM o d e l A n d V i e w withoutanyassociatednamespecified.
p u b l i cc l a s sD i s p l a y S h o p p i n g C a r t C o n t r o l l e ri m p l e m e n t sC o n t r o l l e r{ p u b l i cM o d e l A n d V i e wh a n d l e R e q u e s t ( H t t p S e r v l e t R e q u e s tr e q u e s t ,H t t p S e r v l e t R e s p o n s er e s p o n s e ){ L i s tc a r t I t e m s=/ /g e taL i s to fC a r t I t e mo b j e c t s U s e ru s e r=/ /g e tt h eU s e rd o i n gt h es h o p p i n g M o d e l A n d V i e wm a v=n e wM o d e l A n d V i e w ( " d i s p l a y S h o p p i n g C a r t " ) ;< -t h el o g i c a lv i e wn a m e m a v . a d d O b j e c t ( c a r t I t e m s ) ;< -l o o km a ,n on a m e ,j u s tt h eo b j e c t m a v . a d d O b j e c t ( u s e r ) ;< -a n da g a i nm a ! } r e t u r nm a v ;

TheM o d e l A n d V i e w classusesaM o d e l M a p classthatisacustomM a p implementationthatautomaticallygenerates akeyforanobjectwhenanobjectisaddedtoit.Thestrategyfordeterminingthenameforanaddedobjectis,in


http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 25/30

2/3/2014

15. Web MVC framework

the case of a scalar object such as U s e r , to use the short class name of the object's class. The following examplesarenamesthataregeneratedforscalarobjectsputintoaM o d e l M a p instance. Anx . y . U s e r instanceaddedwillhavethenameu s e r generated. Anx . y . R e g i s t r a t i o n instanceaddedwillhavethenamer e g i s t r a t i o n generated. Anx . y . F o o instanceaddedwillhavethenamef o o generated. A j a v a . u t i l . H a s h M a p instance added will have the name h a s h M a p generated. You probably want to be explicitaboutthenameinthiscasebecauseh a s h M a p islessthanintuitive. Addingn u l l willresultinanI l l e g a l A r g u m e n t E x c e p t i o n beingthrown.Iftheobject(orobjects)thatyouare addingcouldben u l l ,thenyouwillalsowanttobeexplicitaboutthename. The strategy for generating a name after adding a S e t , L i s t or array object is to peek into the collection, take the short class nameofthefirstobjectinthecollection,andusethatwith L i s t appendedtothename.Someexampleswillmakethesemantics ofnamegenerationforcollectionsclearer... An x . y . U s e r [ ] array with one or more x . y . U s e r elements addedwillhavethenameu s e r L i s t generated. An x . y . F o o [ ] array with one or more x . y . U s e r elements addedwillhavethenamef o o L i s t generated. A j a v a . u t i l . A r r a y L i s t with one or more x . y . U s e r elementsaddedwillhavethenameu s e r L i s t generated. A j a v a . u t i l . H a s h S e t with one or more x . y . F o o elements addedwillhavethenamef o o L i s t generated. Anemptyj a v a . u t i l . A r r a y L i s t willnotbeaddedatall(ineffect,thea d d O b j e c t ( . . ) callwillessentiallybe anoop).

What,noautomaticpluralisation? Spring Web MVC's conventionover configuration support does not support automatic pluralisation. That is, you cannot add a L i s t of P e r s o n objects to a M o d e l A n d V i e w and have the generatednamebep e o p l e . This decision was made after some debate, with the Principle of Least Surprisewinningoutintheend.

15.10.3TheViewR e q u e s t T o V i e w N a m e T r a n s l a t o r
TheR e q u e s t T o V i e w N a m e T r a n s l a t o r interfacedeterminesalogicalV i e w namewhennosuchlogicalviewnameis explicitlysupplied.Ithasjustoneimplementation,theD e f a u l t R e q u e s t T o V i e w N a m e T r a n s l a t o r class. TheD e f a u l t R e q u e s t T o V i e w N a m e T r a n s l a t o r mapsrequestURLstologicalviewnames,aswiththisexample:
p u b l i cc l a s sR e g i s t r a t i o n C o n t r o l l e ri m p l e m e n t sC o n t r o l l e r{ p u b l i cM o d e l A n d V i e wh a n d l e R e q u e s t ( H t t p S e r v l e t R e q u e s tr e q u e s t ,H t t p S e r v l e t R e s p o n s er e s p o n s e ){ / /p r o c e s st h er e q u e s t . . . M o d e l A n d V i e wm a v=n e wM o d e l A n d V i e w ( ) ; / /a d dd a t aa sn e c e s s a r yt ot h em o d e l . . . r e t u r nm a v ; / /n o t i c et h a tn oV i e wo rl o g i c a lv i e wn a m eh a sb e e ns e t }

< ? x m lv e r s i o n = " 1 . 0 "e n c o d i n g = " U T F 8 " ? > < ! D O C T Y P Eb e a n sP U B L I C" / / S P R I N G / / D T DB E A N2 . 0 / / E N " " h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / d t d / s p r i n g b e a n s 2 . 0 . d t d " > < b e a n s > < ! -t h i sb e a nw i t ht h ew e l lk n o w nn a m eg e n e r a t e sv i e wn a m e sf o ru s> < b e a ni d = " v i e w N a m e T r a n s l a t o r "c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . D e f a u l t R e q u e s t T o V i e w N a m e T r a n s l a t o r " < b e a nc l a s s = " x . y . R e g i s t r a t i o n C o n t r o l l e r " > < ! -i n j e c td e p e n d e n c i e sa sn e c e s s a r y> < / b e a n > < ! -m a p sr e q u e s tU R L st oC o n t r o l l e rn a m e s> < b e a nc l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . m v c . s u p p o r t . C o n t r o l l e r C l a s s N a m e H a n d l e r M a p p i n g " / > < b e a ni d = " v i e w R e s o l v e r "c l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . v i e w . I n t e r n a l R e s o u r c e V i e w R e s o l v e r " > < p r o p e r t yn a m e = " p r e f i x "v a l u e = " / W E B I N F / j s p / " / > < p r o p e r t yn a m e = " s u f f i x "v a l u e = " . j s p " / > < / b e a n > < / b e a n s >

Noticehowintheimplementationoftheh a n d l e R e q u e s t ( . . ) methodnoV i e w orlogicalviewnameiseverseton theM o d e l A n d V i e w thatisreturned.TheD e f a u l t R e q u e s t T o V i e w N a m e T r a n s l a t o r istaskedwithgeneratinga logical viewname from the URL of the request. In the case of the above R e g i s t r a t i o n C o n t r o l l e r , which is used in conjunction with the C o n t r o l l e r C l a s s N a m e H a n d l e r M a p p i n g , a request URL of
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 26/30

2/3/2014

15. Web MVC framework


h t t p : / / l o c a l h o s t / r e g i s t r a t i o n . h t m l results in a logical view name of r e g i s t r a t i o n being generated by the D e f a u l t R e q u e s t T o V i e w N a m e T r a n s l a t o r . This logical view name is then resolved into the / W E B I N F / j s p / r e g i s t r a t i o n . j s p viewbytheI n t e r n a l R e s o u r c e V i e w R e s o l v e r bean.

Tip Youdonotneedtodefinea D e f a u l t R e q u e s t T o V i e w N a m e T r a n s l a t o r beanexplicitly.Ifyoulike thedefaultsettingsofthe D e f a u l t R e q u e s t T o V i e w N a m e T r a n s l a t o r ,youcanrelyontheSpring WebMVC D i s p a t c h e r S e r v l e t to instantiate an instance of this class if one is not explicitly configured. Of course, if you need to change the default settings, then you do need to configure your own D e f a u l t R e q u e s t T o V i e w N a m e T r a n s l a t o r bean explicitly. Consult the comprehensive Javadoc for the D e f a u l t R e q u e s t T o V i e w N a m e T r a n s l a t o r classfordetailsofthevariouspropertiesthatcanbeconfigured.

15.11ETagsupport
An ETag (entity tag) is an HTTP response header returned by an HTTP/1.1 compliant web server used to determinechangeincontentatagivenURL.Itcanbeconsideredtobethemoresophisticatedsuccessortothe L a s t M o d i f i e d header. When a server returns a representation with an ETag header, the client can use this headerinsubsequentGETs,inanI f N o n e M a t c h header.Ifthecontenthasnotchanged,theserverreturns3 0 4 : N o tM o d i f i e d . SupportforETagsisprovidedbytheservletfilter S h a l l o w E t a g H e a d e r F i l t e r .ItisaplainServletFilter,andthus can be used in combination with any web framework. The S h a l l o w E t a g H e a d e r F i l t e r filter creates socalled shallowETags(asopposedtodeepETags,moreaboutthatlater).Thefiltercachesthecontentoftherendered JSP(orothercontent),generatesanMD5hashoverthat,andreturnsthatasanETagheaderintheresponse. Thenexttimeaclientsendsarequestforthesameresource,itusesthathashastheI f N o n e M a t c h value.The filterdetectsthis,renderstheviewagain,andcomparesthetwohashes.Iftheyareequal,a3 0 4 isreturned.This filterwillnotsaveprocessingpower,astheviewisstillrendered.Theonlythingitsavesisbandwidth,asthe renderedresponseisnotsentbackoverthewire. YouconfiguretheS h a l l o w E t a g H e a d e r F i l t e r inw e b . x m l :
< f i l t e r > < f i l t e r n a m e > e t a g F i l t e r < / f i l t e r n a m e > < f i l t e r c l a s s > o r g . s p r i n g f r a m e w o r k . w e b . f i l t e r . S h a l l o w E t a g H e a d e r F i l t e r < / f i l t e r c l a s s > < / f i l t e r > < f i l t e r m a p p i n g > < f i l t e r n a m e > e t a g F i l t e r < / f i l t e r n a m e > < s e r v l e t n a m e > p e t c l i n i c < / s e r v l e t n a m e > < / f i l t e r m a p p i n g >

15.12ConfiguringSpringMVC
Spring3introducesam v c XMLconfigurationnamespacethatsimplifiesthesetupofSpringMVCinsideyourweb application.Instead of registering lowlevel beans such as AnnotationMethodHandlerAdapter, you can simply usethenamespaceanditshigherlevelconstructs.Thisisgenerallypreferredunlessyourequirefinergrained controloftheconfigurationatthebeanlevel. The mvc namespace consists of three tags: mvc:annotationdriven, mvc:interceptors, and mvc:viewcontroller. EachofthesetagsisdocumentedbelowandintheXMLschema.

15.12.1mvc:annotationdriven
ThistagregisterstheDefaultAnnotationHandlerMappingandAnnotationMethodHandlerAdapterbeansthatare requiredforSpringMVCtodispatchrequeststo@Controllers.Thetagconfiguresthosetwobeanswithsensible defaultsbasedonwhatispresentinyourclasspath.Thedefaultsare: 1. Support for Spring 3's Type ConversionService in addition to JavaBeans PropertyEditors during Data Binding. A ConversionService instance produced by the o r g . s p r i n g f r a m e w o r k . f o r m a t . s u p p o r t . F o r m a t t i n g C o n v e r s i o n S e r v i c e F a c t o r y B e a n isusedbydefault.This canbeoverridenbysettingthec o n v e r s i o n s e r v i c e attribute. 2. SupportforformattingNumberfieldsusingthe@NumberFormatannotation 3. SupportforformattingDate,Calendar,Long,andJodaTimefieldsusingthe@DateTimeFormatannotation, ifJodaTime1.3orhigherispresentontheclasspath. 4. Supportforvalidating@Controllerinputswith@Valid,ifaJSR303Providerispresentontheclasspath. Thevalidationsystemcanbeexplicitlyconfiguredbysettingthev a l i d a t o r attribute. 5. SupportforreadingandwritingXML,ifJAXBispresentontheclasspath.
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 27/30

2/3/2014

15. Web MVC framework

6. SupportforreadingandwritingJSON,ifJacksonispresentontheclasspath. Atypicalusageisshownbelow:
< ? x m lv e r s i o n = " 1 . 0 "e n c o d i n g = " U T F 8 " ? > < b e a n sx m l n s = " h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / b e a n s " x m l n s : m v c = " h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / m v c " x m l n s : x s i = " h t t p : / / w w w . w 3 . o r g / 2 0 0 1 / X M L S c h e m a i n s t a n c e " x s i : s c h e m a L o c a t i o n = " h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / b e a n s h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / b e a n s / s p r i n g b e a n s 3 . 0 . x s d h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / m v c h t t p : / / w w w . s p r i n g f r a m e w o r k . o r g / s c h e m a / m v c / s p r i n g m v c 3 . 0 . x s d " > < ! -J S R 3 0 3s u p p o r tw i l lb ed e t e c t e do nc l a s s p a t ha n de n a b l e da u t o m a t i c a l l y> < m v c : a n n o t a t i o n d r i v e n / > < / b e a n s >

15.12.2mvc:interceptors
ThistagallowsyoutoregistercustomHandlerInterceptorsorWebRequestInterceptorsthatshouldbeappliedto allHandlerMappingbeans.YoucanalsorestricttheURLpathsspecifcinterceptorsapplyto. AnexampleofregisteringaninterceptorappliedtoallURLpaths:
< m v c : i n t e r c e p t o r s > < b e a nc l a s s = " o r g . s p r i n g f r a m e w o r k . w e b . s e r v l e t . i 1 8 n . L o c a l e C h a n g e I n t e r c e p t o r "/ > < / m v c : i n t e r c e p t o r s >

AnexampleofregisteringaninterceptorlimitedtoaspecificURLpath:
< m v c : i n t e r c e p t o r s > < m v c : i n t e r c e p t o r > < m a p p i n gp a t h = " / s e c u r e / * " / > < b e a nc l a s s = " o r g . e x a m p l e . S e c u r i t y I n t e r c e p t o r "/ > < / m v c : i n t e r c e p t o r > < / m v c : i n t e r c e p t o r s >

15.12.3mvc:viewcontroller
Thistagisashorcutfordefininga P a r a m e t e r i z a b l e V i e w C o n t r o l l e r thatimmediatelyforwardstoaviewwhen invoked.UseitinstaticcaseswhenthereisnoJavaControllerlogictoexecutebeforetheviewgeneratesthe response. Anexampleofviewcontrollerthatforwardstoahomepageisshownbelow:
< m v c : v i e w c o n t r o l l e rp a t h = " / "v i e w n a m e = " h o m e " / >

15.12.4mvc:resources
This tag allows static resource requests following a particular URL pattern to be served by a R e s o u r c e H t t p R e q u e s t H a n d l e r fromanyofalistof R e s o u r c e locations.Thisprovidesaconvenientwaytoserve static resources from locations other than the web application root, including locations on the classpath. The c a c h e p e r i o d property may be used to set far future expiration headers (1 year is the recommendation of optimizationtoolssuchasPageSpeedandYSlow)sothattheywillbemoreefficientlyutilizedbytheclient.The handleralsoproperlyevaluatesthe L a s t M o d i f i e d header(ifpresent)sothata 3 0 4 statuscodewillbereturned asappropriate,avoidingunnecessaryoverheadforresourcesthatarealreadycachedbytheclient.Forexample, toserveresourcerequestswithaURLpatternof / r e s o u r c e s / * * froma p u b l i c r e s o u r c e s directory within the webapplicationroot,thetagwouldbeusedasfollows:
< m v c : r e s o u r c e sm a p p i n g = " / r e s o u r c e s / * * "l o c a t i o n = " / p u b l i c r e s o u r c e s / " / >

Toservetheseresourceswitha1yearfutureexpirationtoensuremaximumuseofthebrowsercacheanda reductioninHTTPrequestsmadebythebrowser:
< m v c : r e s o u r c e sm a p p i n g = " / r e s o u r c e s / * * "l o c a t i o n = " / p u b l i c r e s o u r c e s / "c a c h e p e r i o d = " 3 1 5 5 6 9 2 6 " / >

The m a p p i n g attributemustbeanAntpatternthatcanbeusedby S i m p l e U r l H a n d l e r M a p p i n g ,andthe l o c a t i o n


http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 28/30

2/3/2014

15. Web MVC framework

attribute must specify one or more valid resource directory locations. Multiple resource locations may be specifiedusingacommaseperatedlistofvalues.Thelocationsspecifiedwillbecheckedinthespecifiedorder forthepresenceoftheresourceforanygivenrequest.Forexample,toenabletheservingofresourcesfromboth thewebapplicationrootandfromaknownpathof/ M E T A I N F / p u b l i c w e b r e s o u r c e s / inanyjarontheclasspath, thetagwouldbespecifiedas:
< m v c : r e s o u r c e sm a p p i n g = " / r e s o u r c e s / * * "l o c a t i o n = " / ,c l a s s p a t h : / M E T A I N F / p u b l i c w e b r e s o u r c e s / " / >

Whenservingresourcesthatmaychangewhenanewversionoftheapplicationisdeployed,itisrecommended thatyouincorporateaversionstringintothemapping pattern used to request the resources, so that you may forceclientstorequestthenewlydeployedversionofyourapplication'sresources.Suchaversionstringcanbe parameterizedandaccessedusingSpELsothatitmaybeeasilymanagedinasingleplacewhendeploying newversions. Asanexample,let'sconsideranapplicationthatusesaperformanceoptimizedcustombuild(asrecommended) oftheDojoJavaScriptlibraryinproduction,andthatthebuildisgenerallydeployedwithinthewebapplicationat apathof / p u b l i c r e s o u r c e s / d o j o / d o j o . j s .SincedifferentpartsofDojomaybeincorporatedintothecustom build for each new version of the application, the client web browsers need to be forced to redownload that custombuilt d o j o . j s resourceanytimeanewversionoftheapplicationisdeployed.Asimplewaytoachieve thiswouldbetomanagetheversionoftheapplicationinapropertiesfile,suchas:
a p p l i c a t i o n . v e r s i o n = 1 . 0 . 0

andthentomakethepropertiesfile'svaluesaccessibletoSpELasabeanusingtheu t i l : p r o p e r t i e s tag:
< u t i l : p r o p e r t i e si d = " a p p l i c a t i o n P r o p s "l o c a t i o n = " / W E B I N F / s p r i n g / a p p l i c a t i o n . p r o p e r t i e s " / >

WiththeapplicationversionnowaccessibleviaSpEL,wecanincorporatethisintotheuseofther e s o u r c e s tag:
< m v c : r e s o u r c e sm a p p i n g = " / r e s o u r c e s # { a p p l i c a t i o n P r o p s [ ' a p p l i c a t i o n . v e r s i o n ' ] } / * * "l o c a t i o n = " / p u b l i c r e s o u r c e s / " / >

andfinally,torequesttheresourcewiththeproperURL,wecantakeadvantageoftheSpringJSPtags:
< s p r i n g : e v a le x p r e s s i o n = " @ a p p l i c a t i o n P r o p s [ ' a p p l i c a t i o n . v e r s i o n ' ] "v a r = " a p p l i c a t i o n V e r s i o n " / > < s p r i n g : u r lv a l u e = " / r e s o u r c e s { a p p l i c a t i o n V e r s i o n } "v a r = " r e s o u r c e U r l " > < s p r i n g : p a r a mn a m e = " a p p l i c a t i o n V e r s i o n "v a l u e = " $ { a p p l i c a t i o n V e r s i o n } " / > < / s p r i n g : u r l > < s c r i p ts r c = " $ { r e s o u r c e U r l } / d o j o / d o j o . j s "t y p e = " t e x t / j a v a s c r i p t " >< / s c r i p t >

15.12.5mvc:defaultservlethandler
Thistagallowsformappingthe D i s p a t c h e r S e r v l e t to"/"(thusoverridingthemappingofthecontainer'sdefault Servlet),whilestillallowingstaticresourcerequeststobehandledbythecontainer'sdefaultServlet.Itconfigures a D e f a u l t S e r v l e t H t t p R e q u e s t H a n d l e r with a URL mapping (given a lowest precedence order) of "/**". This handlerwillforward all requests to the default Servlet. To enable this feature using the default setup, simply includethetagintheform:
< m v c : d e f a u l t s e r v l e t h a n d l e r / >

Thecaveattooverridingthe"/"Servletmappingisthatthe R e q u e s t D i s p a t c h e r forthedefaultServletmustbe retrievedbynameratherthanbypath.The D e f a u l t S e r v l e t H t t p R e q u e s t H a n d l e r will attempt to autodetect the default Servlet for the container at startup time, using a list of known names for most of the major Servlet containers(includingTomcat,Jetty,Glassfish,JBoss,Resin,WebLogic,andWebSphere).IfthedefaultServlet hasbeencustomconfiguredwith a different name, or if a different Servlet container is being used where the defaultServletnameisunknown,thenthedefaultServlet'snamemustbeexplicitlyprovidedasinthefollowing example:
< m v c : d e f a u l t s e r v l e t h a n d l e rd e f a u l t s e r v l e t n a m e = " m y C u s t o m D e f a u l t S e r v l e t " / >

15.13MoreSpringWebMVCResources
SeethefollowinglinksandpointersformoreresourcesaboutSpringWebMVC:
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html 29/30

2/3/2014

15. Web MVC framework

TherearemanyexcellentarticlesandtutorialsthatshowhowtobuildwebapplicationswithSpringMVC. ReadthemattheSpringDocumentationpage. ExpertSpringWebMVCandWebFlowbySethLaddandothers(publishedbyApress)isanexcellent hardcopysourceofSpringWebMVCgoodness. Prev PartV.TheWeb Up Home Next 16.Viewtechnologies

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

30/30

You might also like