Tải bản đầy đủ - 0 (trang)
Chapter 13. Struts and Enterprise JavaBeans

Chapter 13. Struts and Enterprise JavaBeans

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

andtheapplicationtiersuppliesthebusinessdataandits

associatedrules.Suchadesignisappropriatewhenthe

scalability,security,andtransactionalneedsofanenterprise

applicationrequireamorerobustcontainer.Thissituationis

whatwewanttoconsiderinthischapter.Whileit'struethatthe

developmentofyourStrutsclassescanbeindependentofthe

modelimplementation,thisdoesrequiresomeeffortonyour

part.Thischaptercoverssomeoftheissuesyouneedto

considerwhendevelopinganinterfacebetweenyourStruts

actionsandanapplicationtier.Inparticular,thefocushereison

interfacingtoamodelbuiltusingEnterpriseJavaBeans(EJB).



ToEJBorNottoEJB?

AstheJ2EEarchitecturegrewinsignificanceforenterpriseapplication

development,itwasoftenassumedthatanapplicationthatdidn'tincludeEJB

wasn'taJ2EEapplicationatall.Therushwasontobuildenterprise-strength

systemsbackedbyEJBcontainersandalltheyhadtooffer.Forcarefully

designedapplicationsthatrequiredthetypeofinfrastructureinherentwithEJB,

thetechnologyprovidedastandards-basedapproachthatledtomanysuccessful

deployments.However,thefocusontheEJBportionofJ2EEalsoledtoitsusein

applicationsthatcouldhavebeenbetterservedbymorelightweightapproaches.

This,alongwithsomedevelopers'disappointmentwiththepaceofEJB's

evolution,hasledtoabacklashagainstusingEJBatall.Developersfallonboth

sidesofthisissue,withsomeintheStrutscommunitybeingquitevocalintheir

criticismofEJB.ThemoremoderateopinionisthatEJBoffersvaluewhereits

strengthsaretrulyneeded,butcanbecostlybothinperformanceand

complexityotherwise.

Thischapterwon'tattempttoarguetheprosandconsofEJB.Thattopicfalls

outsidethescopeofthisbook.Instead,we'llsimplypresumethatyou'vebeen

askedtobuildaStruts-basedwebtierthatneedstointerfacewithanEJB

applicationtier.Withthatasastartingpoint,themainconcernswillbeto

identifythekeyissuesandcomeupwithaneffectiveapproachforaddressing

them.



13.1ImplementingtheStorefrontServiceUsing

EJB

EventhoughthischapterisspecifictoEJB,theintentisstillto

keepthefocusonStruts.Withthatinmind,thediscussionof

EJBimplementationdetailswillbekepttoaminimum.EJBisa

complextopic,butthenatureofseveraldesignpatternsgeared

towardtheinteractionbetweenEJBsandtheirclientsmakes

thisaneasiertaskthanyoumightfirstthink.Afterall,an

overridinggoalofthischapteristodemonstratehowtodesign

anapplicationsothatyourStrutsclassesaren'timpactedby

thechoicetouseanEJBimplementationofthemodel.You

alreadyhaveaheadstartonsomeofthecentralissueshere,

havingseenhowthemodelcomponentofawebapplicationcan

behiddenbehindaserviceinterface.Inparticular,you'veseen

throughtheStorefrontexamplehoweasyitistoswapadebug

modelwithafullimplementationthataccessesadatabase

whenthisdesignapproachisfollowed.

Throughoutthischapter,theStorefrontexamplewillbeusedto

illustratehowanEJBapplicationtiercanbeusedwithaStruts

application.Ifitweren'tfortheremotenatureofaccessingan

EJBfromaclientapplication,thisimplementationchoice

wouldn'tmakeanydifferencetoyou.However,thedistributed

aspectsofEJBmustbetakenintoaccountwhenyourweb-tier

classesaccessthistypeofmodel.Whatyou'llseeinthe

remainderofthischapteraresomerecommendationsonhow

besttoimplementthecodeneededtointerfacewiththe

applicationtier.Keytothisdiscussionisanapproachfor

isolatingthecodethathandleswhat'suniqueaboutEJBsothat

youractionclassesaren'taffected.



13.1.1AQuickEJBOverview



TheEJBspecificationdefinesthreetypesofbeans:entity,

session,andmessage-driven.Eachtypeofbeanhasadifferent

purposewithinanEJBapplication.

Entitybeansprovidetransactionalaccesstopersistentdataand

aremostoftenusedtorepresentrowsstoredinoneormore

relatedtablesinadatabase.Forexample,youmightimplement

CustomerBean,ItemBean,andOrderBeanentityclasses,among

others,tosupporttheStorefrontapplication.Theseentity

beanswouldincorporatethefunctionalityprovidedbythe

correspondingbusinessobjectclassesintheexample

application.Whenentitybeansareused,theytakeonthe

primaryroleofsupplyingtheapplicationmodel.Theyare

expectedtoprovideboththerequireddatapersistence

operationsandthebusinesslogicthatgovernsthedatathey

represent.Becausethemodelshouldbereusableacross

applicationsinanenterprise,entitybeansneedtobe

independentofthetypesofclientsthatultimatelyaccessthe

applicationtier.

Sessionbeansareoftendescribedasextensionsoftheclient

applicationstheyserve.Theycanimplementbusinesslogic

themselves,butmoreoftentheirroleistocoordinatethework

ofotherclasses(entitybeans,inparticular).Theyaremore

closelytiedtotheirclients,sotheprecautionofkeepingentity

beansreusabledoesn'tapplytosessionbeanstothesame

extent.Theapplicationtierisprimarilyconsideredtobethe

applicationmodel,butsessionbeansarealsoreferredtoas

"controllers"becauseofthecoordinationtheydo.Thisis

especiallytruewhensession-beanmethodsareusedto

implementtransactionsthattouchmultiplebusinessobjects.



Sessionbeanscanbeimplementedaseitherstatelessorstateful.A

statelesssessionbeanmaintainsnostatespecifictoitsclient,soa

singleinstancecanefficientlybesharedamongmanyclientsbytheEJB

container.Astatefulbeaninstance,ontheotherhand,isassignedtoa

specificclientsothatstatecanbemaintainedacrossmultiplecalls.

Holdingstateintheapplicationtiercansimplifytheclientapplication



logic,butitmakesitmoredifficulttoscaletoalargenumberofclients.

Typicalwebapplicationsmaintaintheirclientstateintheusersession,

andpossiblythedatabase,insteadofmakinguseofstatefulsession

beans.Forthisreason,we'llfocusonstatelessbeansforourexamples

here.



TheEJB2.0specificationaddedmessage-drivenbeansasthe

thirdbeantypesothatEJBcouldbeintegratedwiththeJava

MessageService(JMS).Message-drivenbeansdifferfromthe

othertwotypesinthattheyrespondasynchronouslyto

requestsinsteadofbeingcalleddirectlybyaclientapplication.

Thecontainerinvokesamessage-drivenbeanwheneveraJMS

messagethatmeetstheselectioncriteriaofthebeanis

received.Forexample,inamorecomplexversionofthe

Storefrontapplication,amessage-drivenbeancouldbeusedto

respondtoanotificationthatanitemisbeingbackordered.The

beancouldberesponsibleforemailinganycustomersthathad

ordersalreadyinplacefortheitem.Message-drivenbeanshave

nodirectinteractionwithclientapplications,sotheyareeven

lessdependentontheclientthanentitybeansare.



13.1.2TheSessionFaỗade

Thefirststepindesigninganinterfacetotheapplicationtieris

toidentifytheentrypointsexposedtoaclientapplication.

Message-drivenbeansaren'tcalleddirectly,sotheydon'tcome

intoplayhere.However,atypicalEJBapplicationcanincludea

numberofsessionandentitybeans.Asalreadypointedout,

standardpracticeistoinsulateentitybeansfromthedetailsof

theclientsothattheycanbereusedinotherapplications.If

yourStrutsactionsweretointeractwithentitybeansdirectly,

thewebtierwouldquicklybecomecoupledtotheobjectmodel

implementedbytheapplicationtier.Thistightcoupling,

combinedwiththedistributednatureofEJB,wouldleadtoa



numberofissues:

ChangesintheEJBobjectmodelwouldrequire

correspondingchangesinthewebtier.

Actionclassesoftenwouldberequiredtoexecutemultiple

remotecallstotheapplicationservertosatisfythebusiness

logicneedsofarequest.

Thebusinesslogicandtransaction-managementcode

neededtoorchestratemultiplecallswouldhavetoexistin

thewebtier.

Toavoidtheseissues,theinterfaceexposedtotheclientsofthe

applicationtierisalmostalwayslimitedtosessionbeans.This

approachiscommonlyreferredtoaseither"sessionwraps

entity"ora"sessionfaáade."Therearequiteafewadvantages

tothisdesign.Whenaclientapplicationmakesasinglecalltoa

session-beanmethodtoperformarequiredoperation,the

sessionbeancaneasilyexecutetherequestasasingle

transaction,andtheimplementationdetailscanbehidden.This

session-beanmethodmightneedtoaccessanumberofentity

beans,orevenothersessionbeans,tosatisfytherequest.No

matterwhattheflowofcontrolisontheapplicationserver,the

complexityishiddenfromtheclient.Becausesessionbeans

becometheonlyclientsoftheentitybeanswhenusinga

sessionfaỗade,there'slittlechanceoftheentitiesbecoming

tiedtoanyparticulartypeofexternalclient.



Eventhoughthediscussionhereassumesthatthebusinessobjectsare

implementedasentitybeans,thisdoesn'thavetobethecaseinanEJB

application.Thesameconcernsandadvantagesthatsupportusinga

sessionfaỗadeapplywhenotherimplementationsareused.Justas

someJavadevelopersdon'tlikeEJB,notallEJBdeveloperslikeentity

beans.Becausethesessionfaỗadehidestheobjectmodelfromthe

client,entitybeanscanbereplacedwithanotherapproach,suchas

Javadataobjects(JDOs)orregulardataaccessobjects(DAOs),



withoutimpactingtheinterfaceexposedtotheclient.



13.1.3TheBusinessInterface

Whenusingasessionfaỗade,youmustfirstdefinethedetails

oftheinterfacebetweenthewebandapplicationtiers.You

mighthavesomequestionsaboutwhichsideshouldbethe

primarydriverofthiscontractbetweenthetwotiers.Earlyin

thedevelopmentoftheStorefrontexample,the

IStoreFrontServiceinterfacewasintroducedtodefinethe

application-tierfunctionalityrequiredtosupportthe

presentationneedsoftheapplication.Inparticular,the

presentationlayerreliesonthesupportingserviceto

authenticateusersandtoprovideproductdescriptionsneeded

tobuildtheonlinecatalog.Takingauser-centeredviewofthe

application,it'seasytoseehowtheservice-layerrequirements

canbedrivenbythewebtier.Afterall,ifacertainviewistobe

built,themodelfunctionalitytosupportithastoexist.

However,oneofthemainreasonstoimplementanenterprise's

businesslogicwithinEJBsistoallowthosebusinessrulesand

thesupportingdatatobeusedtoacrossmultipleapplications.

Thisincludesprovidingsupportforclientsotherthanthose

associatedwithwebapplications.Thisisn'taproblem,because

thedivisionofresponsibilitybetweensessionandentitybeans

helpstoprotectthereusabilityofbusinesslogic.

Becausesessionbeansaretreatedasextensionsoftheclients

theyserve,there'snothingwrongwithdefiningasessionfaỗade

that'sspecifictoaparticularclientapplication.Aslongasyour

entityandmessage-drivenbeansremainindependentofthe

client,it'sreasonabletoimplementasession-beaninterfacein

responsetotherequirementssetforthbyaspecificclient.If

multipleclientviewsofthemodelarerequired,multiplefaỗades



canbeimplementedtosupportthem.

Thefaỗadepresentedbyasessionbeancansupporteitherlocal

orremoteclients.Localclientsofasessionorentitybeancan

onlybeotherEJBsdeployedwithinthesamecontainer.These

clientsaretightlycoupledtothebeanstheyaccess,butthey

offerperformanceadvantageswhencallsneedtobemade

betweenEJBs.Thisisbecausethesemethodcallsusepass-byreferencesemanticsinsteadofbeingtreatedasremotecalls

betweendistributedcomponents.Sessionbeansareoftenlocal

clientsofentitybeans,butit'slesscommonforthemtohave

localclientsoftheirowntosupport.Ourweb-tiercomponents

obviouslyaren'tEJBsrunningwithintheapplicationtier,sowe

careonlyaboutremoteclientsforourpurposeshere.Whatwe

needtodo,then,isdefinetheremoteinterfaceforoursession

faỗade.

Everysessionbeanthatsupportsremoteclientsmusthavea

correspondingremoteinterfacethatextendsthe

javax.ejb.EJBObjectinterface.Thisinterfacedeterminesthe

businessmethodsthatareexposedbythesessionbean.It

mightseemstrange,butyou'llalmostneverseeamethod

explicitlydeclaredinaremoteinterface.Thisisbecauseofan

EJBdesignpatternknownasthebusinessinterface.



Inadditiontoitsremoteinterface,asessionbeansupportingremote

clientsmusthaveahomeinterfacethatextendsjavax.ejb.EJBHome,

animplementationclass,andoneormoreXMLdeploymentdescriptors.

Unliketheremoteinterface,whichdeclaresthebean'sbusiness

methods,thehomeinterfacedefinesfactory-likemethodsforcreating

session-beanreferences.Bydefinition,thebean'smethodsare

implementedbytheimplementationclass.Thedeploymentdescriptors

identifyandconfigureabeanforusewithinaparticularEJBcontainer.

We'lldefineeachpieceforourexampleaswegoalong.



Whenyouthinkofaclassandaninterfacewithwhichit's



associated,youwouldnormallyexpectthattheclasswould

explicitlyimplementthatinterface.Thisisn'ttruewithremote

(orlocal)interfacesinEJB.Instead,thecontainercreatesan

intermediateobject(oftenreferredtoasanEJBObject)to

implementtheremoteinterface.Thisobjectinterceptscalls

madebyclientsofthebean,thendelegatesthemtothe

implementationclassafterperforminganyoperations(suchas

securityortransactionmanagement)thatmightberequired.

InsteadoftheJavacompilerverifyingthatthebeanclass

implementseachofthebusinessmethodsdeclaredbythe

remoteinterface,thatresponsibilityfallstothedeployment

toolsprovidedbythecontainer.Evenabeanclassthatcompiles

withoutanyerrorswillfailatdeploymentifthere'samismatch

betweenitanditsremoteinterface.

Ifyoudeclaredasessionbeantoimplementitsremote

interface,you'dbeguaranteedthatthecompilerwouldcatch

anyproblemswithitsbusiness-methoddeclarations.The

problemisthatyou'dalsohavetoprovidedummy

implementationsofthenon-businessmethodsdeclaredby

javax.ejb.EJBObject.Thesemethodswouldneverbecalled

(they'recalledonlyontheintermediateobjectcreatedbythe

container),buttheywouldhavetobetheretosatisfythe

compiler.Insteadoftakingthisapproach,mostEJBdevelopers

createasecondinterface,knownasthebusinessinterface,that

declaresthebusinessmethodsthatneedtobeexposed.

Declaringtheremoteinterfacetoextendthisinterfaceandthe

beanclasstoimplementitexposestherequiredmethods,so

thecompilercanverifythatthebeanimplementsthem.This

patternprovidesaconvenientstartingpointfordefiningour

clientaccessmechanism.



Theuseofabusinessinterfacealsopreventsprogrammersfrom

accidentallypassingorreturningathisreferencetoaninstanceofa

beanclassthathasbeendeclaredtoimplementitsremoteinterface.

Thistopicisbeyondthescopeofthisbook,buttheshortexplanationis

thattheEJBcontainercanmanagebeaninstancesproperlyonlywhen

they'rereferredtousingonlytheirremote(orlocal)interfaces.Abean



referencecan'tbereturnedinplaceofitsremoteinterfaceifthebean

classimplementsonlyitsbusinessinterface.



ReturningtotheIStorefrontServiceinterfacethateventually

mustbesatisfiedbyourimplementation,recallthatitcontains

methodsrelatedtobothuserauthenticationandtheproduct

catalog.Evenwhenusingasessionfaỗade,youwouldlikely

separatetheseresponsibilitiesintoseparatesessionbeans.This

wouldreducethecomplexityofthesessionbeansinvolvedand

simplifytheirmaintenance.However,giventhatEJBdesignisn't

ourfocushere,ourfirstsimplificationwillbetoassumethatour

faỗadewillconsistofasingleStorefrontsessionbean.You

probablywouldn'tdothisinarealapplication,butonceyou

knowhowtointerfacewithasinglesessionbean,applyingthe

sametechniquetomultiplesessionbeansisstraightforward.A

suitablebusinessinterfacefortheStorefrontsessionbeanis

showninExample13-1.



Example13-1.Thebusinessinterfaceforthe

Storefrontsessionbean

packagecom.oreilly.struts.storefront.service;



importjava.rmi.RemoteException;

importjava.util.List;



importcom.oreilly.struts.storefront.catalog.view.ItemDetailVie

importcom.oreilly.struts.storefront.customer.view.UserView;



importcom.oreilly.struts.storefront.framework.exceptions.*;



/**

*ThebusinessinterfacefortheStorefrontsessionbean

*/

publicinterfaceIStorefront{



publicUserViewauthenticate(Stringemail,Stringpassword)

throwsInvalidLoginException,ExpiredPasswordException,



AccountLockedException,DatastoreException,RemoteExcepti



publicListgetFeaturedItems()throwsDatastoreException,Re



publicItemDetailViewgetItemDetailView(StringitemId)

throwsDatastoreException,RemoteException;

}



ThefirstthingtonoticeabouttheIStorefrontinterfaceisthat

itsmethodsdon'texactlymatchthosedeclaredby

IStorefrontService.Firstofall,ourbusinessinterfacedoesn't



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

Chapter 13. Struts and Enterprise JavaBeans

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

×