Tải bản đầy đủ - 0 (trang)
Chapter 3. Overview of the Struts Framework

Chapter 3. Overview of the Struts Framework

Tải bản đầy đủ - 0trang

3.1ABankingAccountExample

Thissectionintroducesanonlinebankingapplicationthatwillbe

usedtofamiliarizeyouwithStruts.Theexamplepresentedhere

isnotcomplete,butitprovidesanoverviewofthemajor

componentsthatarepresentinallStrutsapplicationsand

showshowthosecomponentsfittogether.Amore

comprehensiveandthoroughshopping-cartexamplewillbe

usedthroughouttherestofthebook.

Mostpeoplearefamiliarwiththeconceptofonlinebanking,so

wewon'tspendtoomuchtimeexplainingthebusiness

requirements.Inshort,theonlinebankingapplicationwillallow

anendusertologintothefinancialinstitution'swebsite,view

accountinformation,andtransferfundsfromoneaccountto

another(assumingtheuserhasmorethanoneaccount).The

usermustpresentavalidsetofcredentialstoenterthesitein

thiscase,anaccessnumberandapersonalidentification

number(PIN).

Iftheuserleavesoneorbothfieldsblank,theapplicationwill

displayaformattedmessageinformingtheuserthatbothfields

arerequired.Iftheuserentersvaluesforbothfieldsbutthe

authenticationfails,theloginscreenwillberedisplayed,along

withaformattederrormessageinformingtheuserthatthe

loginhasfailed.Figure3-1showstheonlinebankinglogin

screenafteraninvalidloginattempthasbeendetected.



Figure3-1.Loginscreenfortheonlinebanking

application



Ifthepropercredentialsareenteredforanaccount,theuseris

takentotheaccountinformationscreen.Thisscreenshowsall

oftheaccountsthattheuserhaswiththefinancialinstitution,

aswellasthecurrentbalanceforeachaccount.

Forthisexample,wearenotgoingtoprovidearobust,fullfledgedsecurityserviceandsecurityrealm.Handlingsecurityin

awebapplicationcanbecomplicated,andthere'snoreasonto

muddythewaterswithitatthemoment.Forthepurposesof

thischapter,we'lluseasimpleJavainterfacethatcontainsa

singlelogin()methodtoauthenticateusers.The

IAuthenticationinterfaceisshowninExample3-1.



Example3-1.TheIAuthenticationinterfaceused

bythebankingapplication

packagecom.oreilly.struts.banking.service;



importcom.oreilly.struts.banking.view.UserView;

/**



*Providesmethodsthatthebankingsecurityserviceshouldim

*/

publicinterfaceIAuthentication{

/**

*Theloginmethodiscalledwhenauserwantstologinto

*theonlinebankingapplication.

*@paramaccessNumber-Theaccountaccessnumber.

*@parampin-Theaccountprivateidnumber.



*@returnsaDTOobjectrepresentingtheuser'spersonaldat



*@throwsInvalidLoginExceptionifthecredentialsareinval

*/

publicUserViewlogin(StringaccessNumber,Stringpin)

throwsInvalidLoginException;

}



TheIAuthenticationinterfacecontainsaverysimplelogin()

method,whichtakestheaccessNumberandpinfromthelogin

page.Iftheauthenticationissuccessful,a



com.oreilly.struts.banking.view.UserViewobjectis

returned.Iftheloginisunsuccessful,an

InvalidLoginExceptionisthrown.

TheUserViewisasimpleJavaBeanthatcanbestoredwithin

theuser'ssessionandusedtodisplaycustomer-specificcontent

intheapplication.Althoughit'snotcompletelyrelevanttothe

currentdiscussion,thesourcelistingfortheUserViewwillbe

shownlaterinthechapter.

Thecom.oreilly.struts.banking.service.SecurityService

classisshowninExample3-2.Itimplementsthe

IAuthenticationinterfacefromExample3-1andallowsthe

applicationtoauthenticateusers.Wearenotgoingto

authenticateagainstasecurityrealmforthisexample,sothe

SecurityServiceclasswillcontainhardcodedlogicto

authenticateusers.



Example3-2.Thesecurityserviceusedbythe

examplebankingapplication

packagecom.oreilly.struts.banking.service;



importcom.oreilly.struts.banking.view.UserView;

/**



*Usedbytheexamplebankingapplicationtosimulateasecuri

*/

publicclassSecurityServiceimplementsIAuthentication{



publicUserViewlogin(StringaccessNumber,Stringpin)

throwsInvalidLoginException{



//Arealsecurityservicewouldchecktheloginagainsta

//Thisexampleishardcodedtoletinonly123/456.

if("123".equals(accessNumber)&&"456".equals(pin)){

/*DummyaUserViewforthisexample.



*Thisdata/objectwouldtypicallycomefromthebusines



*afterproperauthentication/authorizationhadbeendon

*/

UserViewuserView=newUserView("John","Doe");

userView.setId("39017");

returnuserView;

}

else{



//Iftheloginmethodisinvalid,throwanInvalidLoginE

//Createamsgthatcanbeinsertedintoalogfile.



Stringmsg="InvalidLoginAttemptby"+accessNumber+



thrownewInvalidLoginException(msg);

}

}

}



Forthisexampleapplication,wewillauthenticatetheuseronly

iftheaccessNumberenteredis"123"andthepinenteredis

"456".



IftheSecurityServicewerebeingusedinarealapplication,itwould

havetocheckthecredentialsagainstsometypeofsecurityrealm,such

asarelationaldatabaseoranLDAPserver.



Oncetheuserhasloggedinsuccessfully,shemayperformtwo

actions:

Viewanaccountdetail

Logout

Figure3-2showstheaccountinformationscreentowhichthe

useristakenafterasuccessfullogin.Theusercanviewdetailed

informationaboutanaccountbyclickingonthataccount.

Figure3-3showstheaccountdetailscreenforthechecking

accountlistedinFigure3-2.



Figure3-2.Theaccountinformationscreen



Figure3-3.Theaccountdetailscreen



Inatypicalonlinebankingapplication,theuserwouldalsohave



theabilitytotransferfundsfromoneaccounttoanother.Asthe

purposeofthischapteristofamiliarizeyouwiththe

componentsoftheStrutsframework,nottoteachyouthe

correctfunctionalityofawebbankingapplication,thefundstransferfunctionalitywillnotactuallybeimplementedhere(feel

freetoimplementitasapracticalexerciseifyou'dlike!).

Finally,theusermaylogoutoftheapplicationaltogetherby

clickingontheLogoutbutton.Whenshedoesso,shewillbe

loggedoutoftheapplicationandreturnedtotheloginscreen.



3.2LookingattheBigPicture

Nowthatwehavedescribedtheexampleapplicationthatwillbe

thebasisofthischapter'sdiscussion,it'stimetostartlooking

athowwecanimplementitusingtheStrutsframework.

AlthoughChapter1discussedtheMVCpatternintheorderof

model,view,andthencontroller,itdoesn'tnecessarilymake

sensetofollowthatorderasweexploretheStrutscomponents.

Infact,it'smorelogicaltocoverthecomponentsintheorderin

whichtheStrutsframeworkusesthemtoprocessarequest.

Thus,we'lldiscussthecomponentsthatmakeupthecontroller

portionoftheframeworkfirst.



3.2.1TheStrutsComponentPackages

TheStrutsframeworkismadeupofapproximately300Java

classes,dividedinto8corepackages("approximately"isan

appropriatetermbecausetheframeworkiscontinuously

growingandbeingshaped).Inthischapter,we'llfocusononly

thetop-levelpackages.Figure3-4showsthetop-level

packagesandtheirdependencieswithintheframework.



Figure3-4.Theeighttop-levelpackagesinthe

Strutsframework



ThevalidatorpackageshowninFigure3-4doesnotrepresentthe

entiresetofclassesandinterfacesnecessaryfortheValidator

framework.TheseareonlytheStruts-specificextensionsnecessaryto

usetheValidatorframeworkwithStruts.Thereisalsoaninthtop-level

packagenamedconfig,whichconsistsofasingleJavaclass.We'll

ignorethispackagefornow;it'snotrelevanttothediscussioninthis

chapter.



Theframeworkcomponentsarenotarrangedbywhatrolethey

playintheMVCpatternactually,theyarearrangedalittle

haphazardly.Youmighthavenoticedthisbysomeofthe

circulardependenciesshowninFigure3-4.Thishasmoretodo

withhowfasttheframeworkhasevolvedthanwithpoor

decisionsmadebythedesigners.Forexample,theaction

packagecontainssomeclassesforthecontroller,somethatare

usedbytheviewdomain,andevenafewthatprobablywould



havebeenbetteroffintheutilpackage.Whilethismaybe

confusingatfirst,you'lleventuallybecomeaccustomedto

whereeverythingis.Table3-1enumeratesthetop-level

packagesandprovidesbriefdescriptionsoftheirpurposes.A

fewofthesetop-levelpackagesalsocontainsubpackages,

whichwillbecoveredinlaterchapters.

Table3-1.Top-levelpackagesintheStrutsframework

Package

name



Description



action



Containsthecontrollerclasses,theActionForm,ActionMessages,andseveral

otherrequiredframeworkcomponents.



actions



Containsthe"out-of-box"Actionclasses,suchasDispatchAction,thatcanbe

usedorextendedbyyourapplication.



config



Includestheconfigurationclassesthatarein-memoryrepresentationsofthe

Strutsconfigurationfile.



taglib



tiles



upload



util



ContainsthetaghandlerclassesfortheStrutstaglibraries.



ContainstheclassesusedbytheTilesframework.



Includesclassesusedforuploadinganddownloadingfilesfromthelocal

filesystem,usingabrowser.



Containsgeneral-purposeutilityclassesusedbytheentireframework.



validator ContainstheStruts-specificextensionclassesusedbyStrutswhendeploying

thevalidator.TheactualValidatorclassesandinterfacesareinthecommons

package,separatefromStruts.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 3. Overview of the Struts Framework

Tải bản đầy đủ ngay(0 tr)

×