Sie sind auf Seite 1von 4

23/09/2016

SpringMVCTutorial:ConceptsandCodeExamplesDeepakGaikwad.net

SpringMVCTutorial:ConceptsandCodeExamples
DeepakGaikwad.net
SpringMVCTutorialcoversbasicconceptsofSpringalongwithcodeexamplesofallimportantconceptsof
SpringMVC.ThistutorialcanbeaverygoodstartingpointforanynewlearnersofSpringMVC.
WhatisSpringMVCframework?
SpringMVCframeworkis
Spring:Usingdependencyinjectionprinciple
MVC:usingmodelviewcontrollerdesignprinciple
Frameworkthatprovidesbothbuildingblockstobuildapplicationsandfewreadycomponents
Thisframeworkprovidesarchitectureandreadycomponentsthatcanbeusedtodeveloppresentationtier
ofanapplication.Itisalightweightframeworktryingtoovercomemanylimitationsofotherwebtier
frameworkslikeStrutsandWebwork.Thisframeworksupportsrequestandresponsecommunication
throughHTTPrequests.Importantaspectsofthisframeworkarediscussedbelow.
Architecture:
ThisframeworkimplementsmanyJEEpatternsinadditiontowellknownMVCpattern.FrontController,
ApplicationController,InterceptingFilter,ViewHelper,CompositeViewetc.patternscanbeseenworkingin
SpringMVCarchitecture.DispatcherServletisthecorecomponentofSpringMVCframework.Dispatcher
ServletreceivesrequestfromaclientandtakesitthroughnextstepsandSpringframeworkfeatures.This
diagramwillgiveyouabroaderviewofthisarchitecture.ThisSpringMVCTutorialexplainsdetailsofeach
componentbelow.

TheDispatcherServlet:
ThisistheservletinaSpringMVCapplicationdefinedinweb.xmlusing<servlet>element.Itisintegrated
withrestofthebeansandSpringcontainerthroughtheconfigurationxmlnamedas<servletname>
servlet.xml.DispatcherServletreceivesallrequestsfromclients,executesthecommonpartofit,delegates
specificimplementationtothecontrollers,receivesresponseinModelandViewform,i.e.dataandview
format,getsviewreadytorender,andsendsresponseback.Thisisresponsibleforreadingallconfiguration
andusingthereadycomponentsofthisframework.
Controllers:
DispatcherServletdelegatestherequesttothecontrollerstoexecutethefunctionalityspecificpartofit.
Therearemanyabstractcontrollersavailableinthisframeworkwhichsupportspecifictasks.Eachabstract
controllerprovidesamethodtobeoverriddenbythecontrollers.

http://www.deepakgaikwad.net/index.php/2009/03/31/springmvctutorialconceptsandcodeexamples.html

1/4

23/09/2016

SpringMVCTutorial:ConceptsandCodeExamplesDeepakGaikwad.net

AbstractController:responsibleforprovidingservicesapplicabletoanykindofHTTPrequest.
ConfigurableattributesavailablearesupportedMethodsGET/POST,requireSession,
synchronizeOnSession,cacheSession,useExpiresHeader,useCacheHeader.Override
handleRequestInternal(HttpServletRequest,HttpServletResponse)method.
ParameterizableViewController:SpecifiesviewnametoreturnWebApplicationContext.
UrlFilenameViewController:InspectsURL,retrievesfilenameofthefilerequestandusesthatasaview
name.
MultiActionController:HandlesmultiplerequestsandneedsMethodNameResolveror
ParameterMethodNameResolvertoworkwith.Onemethodrepresentsoneactioninthiscontroller.
AbstractCommandController:Populatescommandobjectwithrequestparametersavailablein
controller.Offersvalidationfeaturesbutdoesnotofferformfunctionality.
AbstractFormController:Modelsformsusingcommandobjects,validatescommandobject,andmakes
thoseavailableincontroller.Justthatiddoesnotsupporttheviewdetermination.
SimpleFormController:ItdoeseverythingthattheAbstractFormControllerdoesandinadditiontothatit
supportstheviewidentificationandredirection.
AbstractWizardController:Asnamesuggests,itistobeusedforWizardkindofscreengroup,features
requiredinawizardfunctionality(validate,processstart,processfinish,etc.)aresupportedbythis
controller.
CommandObjects:
ThesearePOJOsusedtobindtherequestdataandmakeitavailableonscreen.InStrutsactionforms,we
usedtoextendtheobjectsfromaStrutsclass,butherewedontneedtodoit.Thisisoneoftheadvantages
ofSpring,thatthedataobjectsarenotcoupledwiththeframework.Thereisdifferencebetweenthe
commandobjectandformwhenthesetermsareusedinSpringMVCdocumentation.Commandobject
representsaPOJOthatcanbeboundwiththerequestdata,togetitpopulated.ThetermFormisusedto
describetheprocessofbindingattributesoftheobjectwithfieldsofascreenform.Thus,submission,
resubmissionetc.featuresareassociatedwithrespecttoaform.
HandlingRequests:
WhenarequestcomestotheDispatcherServlet,youmaywanttotakeitthroughdifferentstages.Inthis
framework,youcanconfigurehandlerstodothis.Therearemanyhandlersavailablethatcanbeusedby
providinghandlermappings.Sinceyouwanttotaketherequestthroughdifferentprocesssteps,thehandler
mustbeabletoprocesstherequestforadefinitetaskandforwardtherequesttonexthandlerinchain.For
thisitmustalsocontainthelistofhandlersappliedtothisrequest.
BeanNameUrlHandlerMapping:ExtendsfromAbstractHandlerMapping.MapsincomingHTTPrequest
tothebeannamesconfiguredinapplicationcontexti.e.asabeanname,inapplicationcontext,wegive
urlandthebeanisofacontroller.Thustheurlismappedtoacontroller.
<beanname=/saveCustomer.htm
class=com.myorg.springmvctutorial.web.controller.SaveCustomerController/>
SimpleUrlHandlerMapping:ExtendsfromAbstractHandlerMapping.MorepowerfulandsupportsAnt
styleurlmapping.Thismappingweconfigureattwoplaces.Inweb.xmlwedefinetheurlpattern
supported.
<servletmapping>
http://www.deepakgaikwad.net/index.php/2009/03/31/springmvctutorialconceptsandcodeexamples.html

2/4

23/09/2016

SpringMVCTutorial:ConceptsandCodeExamplesDeepakGaikwad.net

<servletname>springmvctutorial</servletname>
<urlpattern>*.html</urlpattern>
</servletmapping>
Inapplicationcontextxml,wemaptheurlstocontrollerdefinitions.
<beanclass=org.springframework.web.servlet.handler.SimpleUrlHandlerMapping>
<propertyname=mappings>
<value>
/*/saveCutomer.htm=saveCustomerController
</value>
</property>
</bean>
HandlerIntercepter:Implementerofthisinterceptcanimplementthreemethodsofthisintercepter,one
thatiscalledbeforetheactualhandlerexecution,secondafterthehandlerexecutionandlastoneafter
thecompleterequestprocessing.HandlerscanbeconfiguredusingSimpleUrlHandlerMapping
configurationinapplicationcontext.
ViewResolving:
Aftercompletionofrequestprocessingbyacontroller,weneedtoredirectittoaview.Controllergivesa
viewnameandDispatcherServletmapstheviewnametoanappropriateviewbasedontheconfiguration
providedandredirects/forwardstherequesttothatview.SpringMVCprovidesfollowingtypesofview
resolvers.Wecanhavemultipleviewresolverschainedintheconfigurationfiles.
AbstractCachingViewResolver:Extendingthisresolverprovidesabilitytocachetheviewsbefore
actuallycallingtheviews.
XMLViewResolver:TakesviewconfigurationinxmlformatcompliantwithDTDofSpringsbeanfactory.
DefaultconfigurationissearchedinWEBINF/views.xml.
ResourceBundleViewResolver:Definitionsaresearchedinresourcebundlei.e.propertyfiles.Default
classpathpropertyfileissearchedwithnameviews.properties.
UrlBasedViewResolver:Straightforwardurlsymbolmappingtoview.
InternalResourceViewResolver:SubclassofUrlBasedViewResolverthatsupportsJSTLandTilesview
resolving.
VelocityViewReolver:SubclassofUrlBasedViewResolverusedtoresolvevelocityviews.
FreeMarkerViewResolver:SubclassofUrlBasedViewResolverusedtoresolveFreeMarkerviews.
RedirectandForward:
RedirectingcanbeachievedeitherbycontrollerreturninganinstanceofRedirectViewclassofSpring,orby
prefixingthereturnviewnamebyredirect:.Ifweprefixbyforward:thentheresponsewillbeforwarded.
Internationalization:
http://www.deepakgaikwad.net/index.php/2009/03/31/springmvctutorialconceptsandcodeexamples.html

3/4

23/09/2016

SpringMVCTutorial:ConceptsandCodeExamplesDeepakGaikwad.net

Thisisusefulformultilingualsupport.DispatcherServletcallsRequestContext.getLocale()methodand
retrievesthelocale.Wecanaddinterceptorsandlocaleresolverstodothis.Therearefewlocaleresolvers
availableinSpringMVC,wecantellfromwherethelocaleisretrievedbylookingattheirname
AcceptHeaderLocaleResolver,CookieLocaleResolver,SessionLocaleResolver.LocaleChangeInterceptor
canbeconfiguredtotrapthelocalechange.Itcanbeusedtosettheviewlanguagebasedonthelocale.
ThemeBasedPresentation:
Themeisusedinmanybloggingtoolstochangethelookandfeeltogivebetteruserexperience.This
conceptisnowavailableinSpringMVC.Staticfiles(e.g.css)andimagesconstituteatheme.Wecandefine
athemeusingResourceBundleThemeSourceandusethemeresolversfromFixedThemeResolver,
SessionThemeResolver,andCookieThemeResolvertoapplytheselectedtheme.
SpringMVCMultipartSupport:
SpringMVChasorg.springframework.web.multipartpackagetosupportmultiparti.e.fileuploadrequests.
MultipartResolverimplementationscanbeusedtoresolvetheserequests.
ExceptionHandling:
Thisframeworkallowsyoutomapexceptionstoviews.ImplementationsofHandlerExceptionResolver,e.g.
SimpleMappingExceptionResolvercanbeusedtomapandExceptionwithaerrorpage.
SpringMVCTutorialCodeExamples:
FollowingarticleswilltakeyouthroughthedetailcodeexamplesofimportantSpringMVCTutorialconcepts.

http://www.deepakgaikwad.net/index.php/2009/03/31/springmvctutorialconceptsandcodeexamples.html

4/4

Das könnte Ihnen auch gefallen