You are on page 1of 15

StartingSpringMVCTutorial

Part1of8TutorialSet ByKenWilliamson

DrivenSolutions www.drivensolutions.com
Copyright2007DrivenSolutions

Introduction

1. Whoshouldusethistutorial? Thistutorialisintendedforentrylevelsoftwareengineersanddevelopersinterestedin learningSpringMVC.NopriorknowledgeofSpringMVCisrequired,butthistutorialdoes assumeapriorknowledgeofJavaandJ2EE.Itisalsoassumedthatthereaderhasprior knowledgeofwebapplicationsoftwaredevelopment. ThistutorialstartsfromtheverybeginningofbuildingaSpringMVCapplicationandgives stepbystepinstructionsonhowtobuildanddeployaSpringMVCapplication.Allcodeand configurationfilesareexplainedtogivetheuseranunderstandingofhowtheapplication functions.

2. WhatisSpringMVCandwhyshoulditbeused? SpringMVCisanOpenSourceJavabasedwebapplicationframeworkdesignedforusewith agiledevelopmentmethodsandespeciallytheXP(ExtremeProgramming)method.Spring MVCprovidesawaytoquicklydevelopwebapplicationsthatfollowtheModelView Controllerdesignpatternthatprovidesfortheisolationofviewcode,controllercode,and dataaccesscode. DevelopersandengineersmightquestionwhyanotherMVCframeworkisneeded.Spring MVC,however,offersthefollowingadvantagesoveritstwoclosestcompetitors,Strutsand JavaServerFaces: SpringMVCisverylightweightwhichtranslatestomuchlessdevelopedcodeinthe weblayer.Thisalsotranslatestoshorterdevelopmentcycles. SpringMVCisdesignedtomakefulluseoftestdrivendevelopmentmethodologies byusingPOJO(PlainOldJavaObject)thatworkwellwithtestplatformssuchas JUNIT. SpringMVCisveryflexiblewhichtranslatestotheabilitytoeasilyinterfaceother softwaremodulesintoSpringMVC. SpringMVCincludesacollectionoftaglibrariesforuseinsidewebpagestohelp reducetheactualamountofrequiredcodeinsideeachpage.Developerscanalso easilyincorporatetaglibrariesfromotherplatformssuchasStrutsifneeded. SpringMVCismucheasiertolearnandusethanStrutsorJavaServerFacesand allowsdeveloperstoquicklyproducewebapplication.

3. Whyusethistutorial. Thistutorialisdesignedtohelpthereadereasilyunderstandthedevelopmentprocesses requiredmySpringMVC.Thereadercanfollowastepbystepproceduretodeveloptheir firstapplication.Thereadercanalsoreferbacktothistutorialforreferencewhenneed. 4. Whatthistutorialcontains: Thistutorialcontainsthefollowingsections: Whatyouneed Buildingyourproject Writingtherequiredcode Configuringtheapplication Deployingtheapplication Testingtheapplication 5. Howtousethistutorial. Thebestwaytousethistutorialistostartatthebeginningandfolloweachdescribed procedureasrecommendedbythetutorial.Onceeachprocessiscompleted,thereaderisleft withafunctionaltemplateapplicationthatservesasafoundationforfuturedevelopment projects.

BuildingYourFirstSpringMVCApplication

Whatyouwillneed 1. Java1.5orgreaterSDK DownloadthelatestfullJavaSESDKfromwww.java.sun.com Followtheinstallationinstructionsprovidedwiththedownload. 2. MyEclipseIDE DownloadMyEclipseIDE(thereisatrialversionavailablewitha30daylicense)at www.myeclipseide.com Followtheinstallationinstructionsprovidedwiththedownload. 3. Tomcat5.5orlater DownloadthelatestTomcatathttp://tomcat.apache.org Placedtheunzippedapachetomcatxxxxfolderinthedirectoryofyouchoice. FollowtheMyEclipseIDEinstructionsonhowtoinstallapplicationserversandinstall Tomcat. BuildingawebProject Onceyouhavetherequiredcomponents,youcanstartbuildingyourfirstapplication. 1. OnthetopmenuofMyEclipse,goto:(seefigure1.1) File>newandclickProject ClickWebProject 2. Pressnext 3. NametheprojecthelloWebWorld 4. SelectJ2EE1.4 5. SelecttheboxlabeledAddJSTL1.0Libraries 6. Pressfinish

Figure1.1 7. ClickontheprojecthelloWebWorld 8. Onthetopmenu: ClickMyEclipsefromthemenu ClickAddSpringCapabilitiesfromthecontextmenu 9. Selectthefollowingboxes:(seefigure1.2) Spring2.0J2EELibraries SpringTestingSupportLibraries Spring2.0WebLibraries 10. Leaveeverythingelseatdefault 11. Pressfinish 12. Thiscompletestheinitialprojectsetup. 13. ContinuewiththenextsectionWritingtherequiredcode.

Figure1.2

Writingtherequiredcode Inthissection,youbuildtheapplicationstructureandeditthefilesneededtocompletetheapplication. Buildtheapplicationstructure: 1. ClickWebRoot/WEBINF: Doubleclickweb.xml(Thisfileconfiguresthewebapplication) Addthecodelistedinredbelow:(seefigure1.3)

<?xmlversion="1.0"encoding="UTF8"?> <webappversion="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/webapp_2_4.xsd"> <servlet> <servletname>helloWebWorld</servletname> <servletclass>org.springframework.web.servlet.DispatcherServlet</servletclass> <loadonstartup>1</loadonstartup> </servlet> <servletmapping> <servletname>helloWebWorld</servletname> <urlpattern>*.htm</urlpattern><!allowsjsppagestobeaccessedwith.htm extension> </servletmapping> <welcomefilelist> <welcomefile>/index.jsp</welcomefile> </welcomefilelist> </webapp>

Figure1.3(web.xml) ThehelloWebWorldservletconfigurationisusedtoloadtheSpringcontextatstartupoftheweb application.Noticetheservleturlmapping.Mappingallpagestoahtmextensionallowsyoutohide theapplicationimplementationtypeandthereforeallpagesappeartobestandardhtmpages.

2. ClickWebRoot/WEBINF: Onthetopmenuselect File>new>folder namethenewfolderjsp WeplacealljsppagesinsidetheWEBINFfolderwheretheyareunreachablebyawebbrowser.By doingthis,wepreventusersfromnavigatingdirectlytoajsppageitself. 3. ClickWebRoot/WEBINF/jsp Onthetopmenuselect File>new>JSP NametheJSPhelloWebUser.jsp(Thisisoneoftwowebpagesintheapplication) Addthecodelistedinfigure1.4

<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF8"%> <% Stringpath=request.getContextPath(); StringbasePath=request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/"; %> <!DOCTYPEHTMLPUBLIC"//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <basehref="<%=basePath%>"> <title>MyJSP'helloWebWorld.jsp'startingpage</title> <metahttpequiv="pragma"content="nocache"> <metahttpequiv="cachecontrol"content="nocache"> <metahttpequiv="expires"content="0"> <metahttpequiv="keywords"content="keyword1,keyword2,keyword3"> <metahttpequiv="description"content="Thisismypage"> <! <linkrel="stylesheet"type="text/css"href="styles.css"> > </head> <body> HelloWebUser<br> <br> <formmethod='post'>FirstName: <inputname="firstName"><br> <br> <br> LastName:<inputname="lastName"><br> <br> Age:&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input name="age"><br> <br> Location:&nbsp;&nbsp;<inputname="location"><br> <br> <br> <inputname="submit"value="Submit"type="submit"><br> <br><br><br> </form> </body> </html>

Figure1.4(helloWebUser.jsp)

Noticethattheformtaghasnoactionattribute.TheactionisactuallymappedinthetheSpring configurationfile.Wewillseethisfilelater.

4. Followstep3andcreateanotherJSP NametheJSPgreetings.jsp(Thisisthesecondwebpageintheproject) Addthecodelistedinfigure1.5


<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF8"%> <%@taglibprefix="c"uri="http://java.sun.com/jstl/core"%> <%@taglibprefix="fmt"uri="http://java.sun.com/jstl/fmt"%> <% Stringpath=request.getContextPath(); StringbasePath=request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/"; %> <!DOCTYPEHTMLPUBLIC"//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <basehref="<%=basePath%>"> <title>MyJSP'greetings.jsp'startingpage</title> <metahttpequiv="pragma"content="nocache"> <metahttpequiv="cachecontrol"content="nocache"> <metahttpequiv="expires"content="0"> <metahttpequiv="keywords"content="keyword1,keyword2,keyword3"> <metahttpequiv="description"content="Thisismypage"> <! <linkrel="stylesheet"type="text/css"href="styles.css"> > </head> <body> <tablestyle="textalign:left;width:727px;height:349px;" border="0"cellpadding="2"cellspacing="2"> <tbody> <tr> <td>Hello<b>${webUserInfo.firstName}</b><b>${webUserInfo.lastName}</b>. Howareyoutoday.<br><br> Youarenow<b>${webUserInfo.age}</b>andyoulivein<b>$ {webUserInfo.location}</b>. <br></td> </tr> </tbody> </table> </body> </html>

Figure1.5(greetings.jsp NoticetheELtagsusedinthegreetings.jsppage.WebUserInfoisacommandbeanusedtoholdall pagevariables.ThecommandbeanisconfiguredlaterandispopulatedbytheSpringMVCframework.

5. Clickthesrcfolderand: Onthetopmenuclick: File>new>Package NamethePackagecom.driven.solutions.commandClasses Clickthepackageaddedaboveandclick: File>new>classandnametheclassWebUserInfo.javaandaddthecodelistedinfigure 1.6(TheobjectcreatedfromthisclassholdsthedatafromhelloWebUsers.jsp)


Alsoaddanotherpackage:com.driven.solutions.controllers Addtwoclassestothispackage,HelloWebWorldFormController.javaand GreetingController.javaandaddthecodelistedinfigures1.7and1.8(Theseclasses aretheSpringMVCcontrollerclassesandtheobjectscreatedfromtheseclassescontrol theapplicationflow)

packagecom.driven.solutions.commandClasses; public classWebUserInfo{ privateStringfirstName;//javabeanusedtoholdpagevalues privateStringlastName; privateIntegerage; privateStringlocation; publicIntegergetAge(){ returnage; } publicvoidsetAge(Integerage){ this.age=age; } publicStringgetFirstName(){ returnfirstName; } publicvoidsetFirstName(StringfirstName){ this.firstName=firstName; } publicStringgetLastName(){ returnlastName; } publicvoidsetLastName(StringlastName){ this.lastName=lastName; } publicStringgetLocation(){ returnlocation; } publicvoidsetLocation(Stringlocation){ this.location=location; } }

Figure1.6(WebUserInfo.java)

packagecom.driven.solutions.controllers; importorg.springframework.web.servlet.mvc.Controller; importorg.springframework.web.servlet.ModelAndView; importorg.springframework.web.servlet.view.RedirectView; importcom.driven.solutions.commandClasses.WebUserInfo; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjava.io.IOException; importjava.util.Map; importjava.util.HashMap; importorg.apache.commons.logging.Log; importorg.apache.commons.logging.LogFactory; publicclassGreetingsControllerimplementsController{//onlyneedtoimplementControllerbecauseno//formisusedon thegreetings.jsppage publicModelAndViewhandleRequest(HttpServletRequestrequest,HttpServletResponseresponse)throws Exception{ WebUserInfowebUserInfo=(WebUserInfo)request.getSession().getAttribute("webUserInfo");//getweb pagevalues returnnewModelAndView("greetings","webUserInfo",webUserInfo);//forwardwebpage//valuesto newwebpage } }

Figure1.7(GreetingsController.java)

packagecom.driven.solutions.controllers; importorg.springframework.web.servlet.mvc.SimpleFormController; importorg.springframework.validation.BindException; importorg.springframework.web.servlet.ModelAndView; importorg.springframework.web.servlet.view.RedirectView; importcom.driven.solutions.commandClasses.WebUserInfo; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjava.io.IOException; importjava.util.Map; importjava.util.HashMap; importorg.apache.commons.logging.Log; importorg.apache.commons.logging.LogFactory; publicclassHelloWebWorldFormControllerextendsSimpleFormController{//mustextendthe//SimpleFormController becauseaformisonthe //helloWebUser.jsppagethatismappedtothiscontroller protectedfinalLoglogger=LogFactory.getLog(getClass()); publicModelAndViewonSubmit(HttpServletRequestrequest,HttpServletResponseresponse,Objectcommand, BindExceptionerrors) throwsServletException{ WebUserInfowebUserInfo=(WebUserInfo)command;//getwebpagevalues request.getSession().setAttribute("webUserInfo",webUserInfo);//putwebpagevaluesinrequest//objecttobe forwardedtonewpage returnnewModelAndView(newRedirectView(getSuccessView()));//sendtothewebpage//configuredasthe successViewpage. } }

Figure1.8(HelloWebWorldFormController) NoticethattheHelloWebWorldFormControllerextendstheSimpleFormControaller.Doingthisallows ustooverridetheonSubmitmethod.Doingthisalsoprovidesotherfunctionality.Formoredetail, researchtheSimpleFormControlleratwww.springframework.org. Configuringtheapplication 6. ClickWebRoot/WEBINF AddthefollowingfilehelloWebWorldservlet.xml(ThisistheSpringMVCconfiguration filewhereallthecomponentsoftheapplicationaretiedtogether): Enterthecodelistedinfigure1.9

<?xmlversion="1.0"encoding="UTF8"?> <!DOCTYPEbeansPUBLIC"//SPRING//DTDBEAN//EN" "http://www.springframework.org/dtd/springbeans.dtd"> <! Applicationcontextdefinitionfor"springapp"DispatcherServlet. > <beans><!configuresthecontroller> <beanid="helloWebWorldForm" class="com.driven.solutions.controllers.HelloWebWorldFormController"> <propertyname="sessionForm"><value>true</value></property> <propertyname="commandName"><value>webUserInfo</value></property> <property name="commandClass"><value>com.driven.solutions.commandClasses.WebUserInfo</value> </property> <propertyname="formView"><value>helloWebUser</value></property> <propertyname="successView"><value>greetings.htm</value></property> </bean><!configuresthecontroller> <beanid="greetingsController" class="com.driven.solutions.controllers.GreetingsController"/> <beanid="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <propertyname="mappings"> <props><!mapswebpagestothecontrollers> <propkey="/helloWebUser.htm">helloWebWorldForm</prop> <propkey="/greetings.htm">greetingsController</prop> </props> </property> </bean> <beanid="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <propertyname="viewClass"> <value>org.springframework.web.servlet.view.JstlView</value> </property><!configuresprefixandsuffixforwebpagesinsidethe addedjspfolder> <propertyname="prefix"><value>/WEBINF/jsp/</value></property> <propertyname="suffix"><value>.jsp</value></property> </bean> </beans>

Figure1.9(helloWebWorldservlet.xml)

ThehelloWebWorldservlet.xmlistheSpringMVCconfigurationfile.Asseen,weconfigureeach controllerandthecommandbeansused.Wealsoconfiguretheinputpage(formView)andtheoutput page(successView)oftheformcontroller.NoticealsothatweconfiguretheurlMappingbymapping eachhtmpagetothecontrollerthathandlesthepage.

Deployingtheapplication 7. PresstheDeploybuttononMyEclipsetodeploytheapplication.

Oncetheapplicationisdeployed,wecanstarttestingtheoperation. Testingtheapplication 8. PresstheStartbuttononMyEclipsetostartTomcat. 9. Startawebbrowserandenter: http://localhost:8080/helloWebWorld/ helloWebUser.htm 10. Enteryourfirstname,lastname,ageandlocation. 11. PressSubmit 12. Youshouldseethegreetingspageshowingyourfirstandlastname,ageandlocation. 13. Congratulation;youjustcompletedyourfirstSpringMVCapplication.

Part2ofthistutorialwillcoverinterfacingtheMVClayertothebusinesslogiclayer. Part3ofthistutorialwillcoverusingJPAandHibernate Part4ofthistutorialwillcoverusingJPAandToplink. Part5ofthistutorialwillcoverusingAOPtransactionconcepts Part6ofthistutorialwillcovertaglibrariesforSpringMVC Part7ofthistutorialwillcoverSpringwebapplicationdesignconcepts Part8ofthistutorialwilltieeverythingtogetherwithSpringWebflowdesignconcepts

References IntroductionToSpringFramework.(2005).RetrievedOctober25,2007from http://www.theserverside.com/tt/articles/article.tss?l=SpringFramework. What'snewinSpring2.0,TheWebTier.(2007).RetrievedOctober25,2007from http://static.springframework.org/spring/docs/2.0.x/reference/newin2.html#newin2web WebMVCFramework.(2007).RetrievedOctober25,2007from http://static.springframework.org/spring/docs/2.0.x/reference/mvc.html#mvcformtaglib

You might also like