You are on page 1of 12

Spring Framework Basics with Sample Codes

Author: Declaration: I, hereby declare that this document is based on my/our personal experiences of my/our project members. To the best of my/our knowledge, this document does not contain any material that infringes the copyrights of any other individual or organization including the customers of Infosys. Project Details: roject involved #/$ %nvironment *pplication Type roject Type ,urrent roject Target readers Keywords: #pring .ramework, .rameworks, &ava, &)%%, +/, ntroduction: #pring is a relatively new framework which provides a simpler alternative to #truts for separating presentation layer and business logic. 0ow the 1uestion arises why another framework2 There is a difference between these two frameworks 3 #truts is basically used for handling presentation tier while #pring is mainly a framework used to wire together #ervices 4including 'ata *ccess 5bjects6 that can change without affecting code everywhere throughout the application. That means #pring covers the entire web application from presentation to '*5 layer. 7owever, it is possible to use #truts as the +/, web framework with #pring. The terminology is also different 3 *ction in #truts is replaced by ,ontroller in #pring, (' and (5 classes used with #truts are #ervices in #pring while '*5 remains the same. Terms used w!r!t! Spring: "C # n$ersion o% Control&: THE HOLLYWOOD PRINCIPLE DONT CALL ME, I WILL CALL YOU!! ! ! ! ! ! ! """"""" &ava, &# , '() $eb (ased +aintenance """"""""" 'evelopers, +odule -eads

The basic concept of the Inversion of ,ontrol pattern 4also known as dependency injection6 is that you do not create your objects but describe how they should be created. 8ou don9t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. The I5, container6 is then responsible for connecting the components. A"P #Aspect "riented Programming&: *spect:oriented programming, or *5 , is a programming techni1ue that groups the classes based upon their functionality, classes which can be a part of different functionalities altogether. This means crosscutting behaviors which cut across the typical divisions of responsibility, such as logging and transaction management. The %low in Spring is as %ollows! &# 3 ,50.I; <+- 3 ,50T5--%= 3 #%=/I,% I0T%=.*,% 3 #%=/I,% ,-*## 3 '*5 I0T%=.*,% 3 '*5 ,-*##. This flow is set in an xml file which is known as 'iring.

Pro(lem Statement: To explain using a step by step process, the flow from the presentation layer to the '*5 layer, retrieve data from the database and display the retrieved data on the presentation layer using #pring framework. Solution: lease follow the following steps! 0ote! #ample code is given to this functionality> please make the changes according to your re1uirement.

Assumptions: *.6 The reader is familiar with the +/, architecture. ?. ,reate a &# input. 4say index0ew.jsp6 which takes @sername and assword as

Sample Code %or the solution: #inde)*ew!jsp&

<html> <title>Example :: Spring Application</title> <head> <center><h3>SPRING APPLICA I!N</h3></center> <"cript lang#age$%&a'a"cript% "rc$%("/common)("%> </"cript> </head> <*od+> <,orm name$%"ample-orm% method$%po"t%> <ta*le *order $. /idth$%012% align$center> <tr><th *gcolor$%3A456-7% col"pan$8>Login</th></tr> <tr><td>9"er Name</td><td><inp#t t+pe$%text% name$%#"erName%></td></tr> <tr><td>Pa""/ord</td><td><inp#t t+pe$%pa""/ord% name$%pa""/ord%></td></tr> <tr><td col"pan$8 align$center><inp#t t+pe$%*#tton% name$%*tS#*mit% 'al#e$%S#*mit% onClic:$%;alidate<=%></td></tr> </ta*le> </,orm> </*od+> </html>

). 5n click of A#ubmitB button on this &# , a javascript function 4/alidate6 is called which checks for the mandatory fields and submits the form. Sample Code %or the solution: #common!js&

,#nction ;alidate<= > 'ar #Name $ doc#ment)"ample-orm)#"erName)'al#e? 'ar pa""/ord $ doc#ment)"ample-orm)pa""/ord)'al#e? i,<#Name$$%% @@ pa""/ord$$%%= > alert<%Plea"e enter *oth 'al#e" to "#*mit%=? i,<#Name$$%%= > doc#ment)"ample-orm)#"erName),oc#"<=? ret#rn ,al"e? A el"e > doc#ment)"ample-orm)pa""/ord),oc#"<=? ret#rn ,al"e? A A el"e> doc#ment)"ample-orm)"#*mit<=? A

C. 0ow comes the main part 3 where is this &# submitted to2 There is no action defined in the form. .or this we will have to create an entry in the web.xml file. 4In terms of #truts : It is as good as creating our own #truts:,onfig.xml file6 Sample Code %or the solution: #we(!)ml&

<Bxml 'er"ion$%.)1% encoding$%9 -CD%B><E5!C FPE /e*Capp P9GLIC HC//S#n Iicro"+"tem"J Inc)//5 5 Ke* Application 8)3//ENH Hhttp://(a'a)"#n)com/dtd//e*C appL8L3)dtdH></e*Capp> <"er'let> <"er'letCname>"pringapp</"er'letCname> <"er'letCcla"">org)"pring,rame/or:)/e*)"er'let)5i"patcherSer'let</"er'letC cla""> <loadConC"tart#p>.</loadConC"tart#p> </"er'let> <"er'letCmapping> <"er'letCname>"pringapp</"er'letCname> <#rlCpattern>M)htm</#rlCpattern> </"er'letCmapping> </elcomeC,ileCli"t> </elcomeC,ile> index)("p <//elcomeC,ile> <//elcomeC,ileCli"t> <//e*Capp>

D. The next step is creating springapp:servlet.xml file which will contain the beans and the wiring of the application. 4=emember the name given here should match exactly with the one given in the web.xml6 Sample Code %or the solution: #springapp+ser$let!)ml&

<Bxml 'er"ion$%.)1% encoding$%9 -CD%B> <E5!C FPE *ean" P9GLIC %C//SPRING//5 5 GEAN//EN% %"pringC*ean")dtd%> <ECCC Application context de,inition ,or %"pringapp% 5i"patcherSer'let) <*ean"> <*ean id$%"pringappController% //*ean ,or Controller cla""$%com)a*c)"tr#t"pring)controller)SpringappController%> <propert+ name$%"e""ion-orm%><'al#e>tr#e</'al#e></propert+> <propert+ name$%commandName%><'al#e>login*ean</'al#e></propert+> //login*ean CC>

contain" the getter and "etter method" o, the ,ield" on the indexNe/)("p) <propert+ name$%commandCla""%><'al#e>com)a*c)"tr#t"pring)*ean")LoginGean</'al#e> </propert+> <propert+ name$%,orm;ie/%><'al#e>indexNe/)("p</'al#e></propert+> <propert+ name$%"#cce"";ie/%><'al#e>hello)("p</'al#e></propert+> <propert+ name$%"tringIanip#lator% re,$%a#th)"er'ice%/> //Re,erence to Ser'ice inter,ace) </*ean> <*ean id$%#rlIapping% cla""$%org)"pring,rame/or:)/e*)"er'let)handler)Simple9rlNandlerIapping%> <propert+ name$%mapping"%> <prop"> <prop :e+$%/hello)htm%>"pringappController</prop> </prop"> </propert+> </*ean> <*ean id$%a#th)"er'ice)impl% cla""$%com)a*c)"tr#t"pring)"er'ice)LoginImpl%> <propert+ name$%a#thenticator5A!% re,$%a#thenticator5A!Ser'ice%/> //Re,erence to the 5A! inter,ace) </*ean> <*ean id$%a#th)"er'ice% cla""$%org)"pring,rame/or:)aop),rame/or:)Prox+-actor+Gean%> <propert+ name$%prox+Inter,ace"% 'al#e$%com)a*c)"tr#t"pring)"er'ice)Login%/> <propert+ name$%target% re,$%a#th)"er'ice)impl%/> //Re,erence to the "er'ice implementation cla"") </*ean> <*ean id$%a#th)"er'ice)daoimpl% cla""$%com)a*c)"tr#t"pring)dao)Login5ataIanip#latorImpl%> <propert+ name$%dataSo#rce%> <re, local$%dataSo#rce5G5irect%/> </propert+> //Re,erence to the dataSo#rce5G5irect *ean /hich contain" the connection parameter") </*ean> <*ean id$%a#thenticator5A!Ser'ice% cla""$%org)"pring,rame/or:)aop),rame/or:)Prox+-actor+Gean%> <propert+ name$%prox+Inter,ace"% 'al#e$%com)a*c)"tr#t"pring)dao)Login5ataIanip#lator%/> <propert+ name$%target% re,$%a#th)"er'ice)daoimpl%/>//Re,erence to the 5A! implementation cla"") </*ean> <*ean id$%dataSo#rce5G5irect% cla""$%org)"pring,rame/or:)(d*c)data"o#rce)5ri'erIanager5ataSo#rce% de"tro+C method$%clo"e%> <propert+ name$%dri'erCla""Name% 'al#e$%"#n)(d*c)od*c)&d*c!d*c5ri'er%/> <propert+ name$%#rl% 'al#e$%(d*c:od*c:5GNAIE %/>

<propert+ name$%#"ername% 'al#e$%9OName%/> <propert+ name$%pa""/ord% 'al#e$%a*cO.830%/> </*ean>//Connection Parameter" </*ean"> // 5o not directl+ connect +o#r component" and "er'ice" together in code *#t de"cri*e /hich "er'ice" are needed *+ /hich component" in a con,ig#ration ,ile) hi" concept i" called Kiring) E. #ince the &# submits itself to the ,ontroller mentioned in the springapp: servlet.xml file, the next step is to create the ,ontroller itself. Sample Code %or the solution: #SpringappController!ja$a&

/MMPac:age 5eclarationMM/ pac:age com)a*c)"tr#t"pring)controller? /MM&a'a Import"MM/ import (a'a)#til)Arra+Li"t? import (a'a)#til)Li"t? import (a'ax)"er'let)http)NttpSer'letReP#e"t? import (a'ax)"er'let)http)NttpSer'letRe"pon"e? import org)"pring,rame/or:)context)ApplicationContext? import org)"pring,rame/or:)context)"#pport)Cla""PathQmlApplicationContext? import org)"pring,rame/or:)'alidation)GindException? import org)"pring,rame/or:)/e*)"er'let)IodelAnd;ie/? import org)"pring,rame/or:)/e*)"er'let)m'c)Simple-ormController? /MMApplication Import"MM/ import com)a*c)"tr#t"pring)*ean")LoginGean? import com)a*c)"tr#t"pring)"er'ice)Login? p#*lic cla"" SpringappController extend" Simple-ormController > //creating a re,erence o, the "er'ice inter,ace Login "tringIanip#lator? /MM M Iethod onS#*mit M Oparam NttpSer'letReP#e"t M Oparam NttpSer'letRe"pon"e M Oparam !*(ect M Oparam GindException M Oret#rn IodelAnd;ie/ M M/ protected IodelAnd;ie/ onS#*mit<NttpSer'letReP#e"t reP#e"tJ NttpSer'letRe"pon"e re"pon"eJ !*(ect commandJ GindException e= thro/" Exception > // +peca"ting the command o*(ect o, the !*(ect cla"" into the

//LoginGean o*(ect to acce"" attri*#te 'al#e" LoginGean loginGean $ <LoginGean=command? re,erence o, //Calling the carr+5ata method o, the "er'ice la+er #"ing //the "er'ice inter,ace String ". $ "tringIanip#lator)carr+5ata<loginGean=? //Calling the ,etch5ata method o, the "er'ice la+er #"ing re,erence o, //the "er'ice inter,ace Li"t dataLi"t $ "tringIanip#lator),etch5ata<loginGean=? //Setting the ret#rned "tring into reP#e"t reP#e"t)"etAttri*#te<%data.%J".=? //Setting the ret#rned li"t into reP#e"t reP#e"t)"etAttri*#te<%dataLi"t%JdataLi"t=? //Ret#rning the 'ie/ ret#rn ne/ IodelAnd;ie/<getS#cce"";ie/<==? A //Getter and Setter method" o, "tringIanip#lator /MM M Oret#rn "tringIanip#lator M/ p#*lic Login getStringIanip#lator<= > ret#rn "tringIanip#lator? A /MM M Oparam login M/ p#*lic 'oid "etStringIanip#lator<Login login= > "tringIanip#lator $ login? A A//End o, cla"" SpringappController

F. *fter the jsp is submitted, the control comes to the on#ubmit method of the controller class 4#ame as the execute method of the #truts *ction class6. The data from the &# is passed to this method using the command object of the 5bject class. The ,ontroller then typecasts the command object of the 5bject class into the -ogin(ean object to access the attribute values. The controller refers to the service interface using the reference of the #ervice interface created in the controller class itself. @sing the reference of the service interface, the controller calls a method of the #ervice class and passes the -ogin(ean object as an argument to this method.

G. The #ervice interface contains the definitions of the methods in the #ervice layer. Sample Code %or the solution: #,ogin!ja$a&

/MMPac:age 5eclarationMM/ pac:age com)a*c)"tr#t"pring)"er'ice? /MM&a'a Import"MM/ import (a'a)#til)Arra+Li"t? import (a'a)#til)Li"t? /MMApplication Import"MM/ import com)a*c)"tr#t"pring)*ean")LoginGean? p#*lic inter,ace Login > //5e,inition o, method carr+5ata p#*lic String carr+5ata<LoginGean loginGean=? //5e,inition o, method ,etch5ata p#*lic Li"t ,etch5ata<LoginGean loginGean=? A//End o, inter,ace Login

8.

.rom the wiring done in springapp:config.xml, the control goes to the implementing class of the #ervice interface. This class receives the data from the ,ontroller class, creates a reference of the '*5 interface and using that reference calls a method of the '*5 layer and passes the login(ean object as an argument to the '*5 layer.

Sample Code %or the solution: #,ogin mpl!ja$a&

/MMPac:age 5eclarationMM/ pac:age com)a*c)"tr#t"pring)"er'ice? /MM&a'a Import"MM/ import (a'a)#til)Arra+Li"t? import (a'a)#til)Li"t? /MMApplication Import"MM/ import com)a*c)"tr#t"pring)*ean")LoginGean? import com)a*c)"tr#t"pring)dao)Login5ataIanip#lator? p#*lic cla"" LoginImpl implement" Login> //Creating a re,erence o, the 5A! inter,ace Login5ataIanip#lator a#thenticator5A!? /MM M Iethod carr+5ata

M Oparam LoginGean M Oret#rn String M/ p#*lic String carr+5ata<LoginGean loginGean= > ret#rn a#thenticator5A!)carr+5ata<loginGean=? A /MM M Iethod ,etch5ata M Oparam LoginGean M Oret#rn Li"t M/ p#*lic Li"t ,etch5ata<LoginGean loginGean= > Li"t dataLi"t $ a#thenticator5A!),etch5ata<loginGean=? ret#rn dataLi"t? A /MM M Oret#rn M/ p#*lic Login5ataIanip#lator getA#thenticator5A!<= > ret#rn a#thenticator5A!? A /MM M Oparam manip#lator M/ p#*lic 'oid "etA#thenticator5A!<Login5ataIanip#lator manip#lator= > a#thenticator5A! $ manip#lator? A A//End o, cla"" LoginImpl

H. The '*5 interface contains the definitions of the methods in the '*5 layer. Sample Code %or the solution: #,oginData-anipulator!ja$a&

/MMPac:age 5eclarationMM/ pac:age com)a*c)"tr#t"pring)dao? /MM&a'a Import"MM/ import (a'a)#til)Arra+Li"t? import (a'a)#til)Li"t? /MMApplication Import"MM/ import com)a*c)"tr#t"pring)*ean")LoginGean? p#*lic inter,ace Login5ataIanip#lator >

//5e,inition o, method carr+5ata p#*lic String carr+5ata<LoginGean loginGean=? //5e,inition o, method ,etch5ata p#*lic Li"t ,etch5ata<LoginGean loginGean=? A//End o, inter,ace Login5ataIanip#lator ?I. The '*5 Implementation class receives the login(ean object from the #ervice Implementation class and contains all the methods in which the database transactions are performed. This class extends &dbc'ao#upport class which is an inbuilt class of #pring framework which provides the &'(, functionality. The 1uery is fired by making an object of the &dbcTemplate class which is again provided by the framework. Sample Code %or the solution: #,oginData-anipulator mpl!ja$a&

/MMPac:age 5eclarationMM/ pac:age com)a*c)"tr#t"pring)dao? /MM&a'a Import"MM/ import (a'a)"Pl)Re"#ltSet? import (a'a)"Pl)SRLException? import (a'a)#til)Arra+Li"t? import (a'a)#til)Li"t? import (a'ax)"Pl)5ataSo#rce? import org)"pring,rame/or:)context)ApplicationContext? import org)"pring,rame/or:)context)"#pport)Cla""PathQmlApplicationContext? import org)"pring,rame/or:)(d*c)core)&d*c emplate? import org)"pring,rame/or:)(d*c)core)Ro/Iapper? import org)"pring,rame/or:)(d*c)core)Ro/IapperRe"#ltReader? import org)"pring,rame/or:)(d*c)core)"#pport)&d*c5aoS#pport? /MMApplication Import"MM/ import com)a*c)"tr#t"pring)*ean")LoginGean? import com)a*c)"tr#t"pring)dto)5ata5 !? p#*lic cla"" Login5ataIanip#latorImpl extend" &d*c5aoS#pport implement" Login5ataIanip#lator > /MM M Iethod carr+5ata M Oparam LoginGean M Oret#rn String M/ p#*lic String carr+5ata<LoginGean loginGean= > //String ret;al#e $ loginGean)get9"erName<= SloginGean)getPa""/ord<=? String #"erName $ loginGean)get9"erName<=? String ret;al#e $ #"erNameS% : -ollo/ing dr#g" are co'ered #nder +o#r plan%?

ret#rn ret;al#e?

/MM M Iethod ,etch5ata M Oparam LoginGean M Oret#rn Li"t M/ p#*lic Li"t ,etch5ata<LoginGean loginGean= > &d*c emplate (t $ get&d*c emplate<=? Li"t dataLi"t $ (t)P#er+<%"elect e,,ectedLdr#gLnmJ alternateLdr#gLnm ,rom gahpt1*d)chngL,ormLdr#gLalt%J ne/ Ro/IapperRe"#ltReader<ne/ a":"Ro/Iapper<===? ret#rn dataLi"t? A cla"" > a":"Ro/Iapper implement" Ro/Iapper /MM M Iethod mapRo/ M Oparam Re"#ltSet M Oparam int M Oret#rn !*(ect M/ p#*lic !*(ect mapRo/<Re"#ltSet r"J int index= thro/" SRLException > 5ata5 ! #"er $ ne/ 5ata5 !<=? #"er)"etE,,ected5r#g<r")getString<%e,,ectedLdr#gLnm%==? #"er)"etAlternate5r#g<r")getString<%alternateLdr#gLnm%==? ret#rn #"er? A A//End o, cla"" a":"Ro/Iapper A//End o, cla"" Login5ataIanip#latorImpl

??. The data is returned to the ,ontroller in the form of a 'T5 object. 4'T5 class contains the getter and setter methods of the fields on the &# .6 ?). The controller sets the received data in the session and returns the control to the target jsp 4return new +odel*nd/iew 4Atarget.jspB6>6. ?C. 5n the target &# , the data is retrieved from the session and displayed to the user using &#T- tags or #criptlets.

.e%erences: 1. http://www-128.ibm.com/developerworks/library/wa-spring1/ 2. http://www.devx.com/Java/Article/221 !

You might also like