the duke’s bank applicationcation. duke’s bank has two clients: a j2ee application client used...

40
1123 32 The Duke’s Bank Application THIS chapter describes the Duke’s Bank application, an online banking appli- cation. Duke’s Bank has two clients: a J2EE application client used by adminis- trators to manage customers and accounts, and a Web client used by customers to access account histories and perform transactions. The clients access the cus- tomer, account, and transaction information maintained in a database through enterprise beans. The Duke’s Bank application demonstrates how all the compo- nent technologies—enterprise beans, J2EE application clients, and Web compo- nents—presented in this tutorial are applied to provide a simple but functional application. Figure 32–1 gives a high-level view of how the components interact. This chap- ter looks at each of the component types in detail and concludes with a discus- sion of how to build, deploy, and run the application.

Upload: others

Post on 16-Mar-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1123

32The Duke’s Bank

Application

THIS chapterdescribestheDuke’s Bankapplication,anonlinebankingappli-cation.Duke’s Bankhastwo clients:a J2EEapplicationclient usedby adminis-tratorsto managecustomersandaccounts,anda Webclient usedby customersto accessaccounthistoriesandperformtransactions.Theclientsaccessthecus-tomer, account,and transactioninformation maintainedin a databasethroughenterprisebeans.TheDuke’s Bankapplicationdemonstrateshow all thecompo-nenttechnologies—enterprisebeans,J2EEapplicationclients,andWeb compo-nents—presentedin this tutorial areappliedto provide a simplebut functionalapplication.

Figure32–1gives a high-level view of how thecomponentsinteract.This chap-ter looks at eachof the componenttypesin detail andconcludeswith a discus-sion of how to build, deploy, and run the application.

Page 2: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1124 THE DUKE’S BANK APPLICATION

Figure32–1 Duke’s Bank Application

Enterprise BeansFigure32–2 takesa closerlook at the accesspathsbetweenthe clients,enter-prisebeans,anddatabasetables.As you cansee,theend-userclients(WebandJ2EEapplicationclients) accessonly the sessionbeans.Within the enterprisebeantier, thesessionbeansareclientsof theentitybeans.On thebackendof theapplication,theentitybeansaccessthedatabasetablesthatstoretheentitystates.

The source code for these enterprise beans is in the <INSTALL>/

j2eetutorial14/examples/bank/src/com/sun/ebank/ejb/ directory.

Page 3: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

SESSIONBEANS 1125

Figure32–2 Enterprise Beans

Session BeansTheDuke’sBankapplicationhasthreesessionbeans:AccountControllerBean,CustomerControllerBean, and TxControllerBean. (Tx standsfor a businesstransaction,suchas transferringfunds.)Thesesessionbeansprovide a client’sview of theapplication’s businesslogic. Hiddenfrom theclientsaretheserver-sideroutinesthat implementthe businesslogic, accessdatabases,managerela-tionships, and perform error checking.

AccountContr ollerBeanThe businessmethodsof the AccountControllerBean sessionbeanperformtasksthat fall into thefollowing categories:creatingandremoving entity beans,managingthe account-customerrelationship,andgetting the accountinforma-tion.

Page 4: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1126 THE DUKE’S BANK APPLICATION

The following methods create and remove entity beans:

• createAccount

• removeAccount

Thesemethodsof the AccountControllerBean sessionbeancall the create

andremove methodsof theAccountBean entity bean.ThecreateAccount andremoveAccount methods throw application exceptions to indicate invalidmethodarguments.The createAccount methodthrows an IllegalAccount-

TypeException if thetypeargumentis neitherChecking, Savings, Credit, norMoney Market. ThecreateAccount methodalsoverifiesthat thespecifiedcus-tomerexists by invoking the findByPrimaryKey methodof the CustomerBean

entitybean.If theresultof thisverificationis false, thecreateAccount methodthrows aCustomerNotFoundException.

The following methods manage the account-customer relationship:

• addCustomerToAccount

• removeCustomerFromAccount

The AccountBean andCustomerBean entity beanshave a many-to-many rela-tionship.A bankaccountmaybe jointly heldby morethanonecustomer, andacustomermay have multiple accounts.Becausethe entity beansusebean-man-agedpersistence,thereareseveral ways to managethis relationship.For moreinformation, see Mapping Table Relationships for Bean-ManagedPersistence(page757).

In the Duke’s Bank application,the addCustomerToAccount and removeCus-

tomerFromAccount methodsof theAccountControllerBean sessionbeanman-agetheaccount-customerrelationship.TheaddCustomerToAccount method,forexample,startsby verifying that thecustomerexists.To createthe relationship,the addCustomerToAccount method inserts a row into thecustomer_account_xref databasetable.In this cross-referencetable,eachrowcontainsthe customerId and accountId of the relatedentities.To remove arelationship,the removeCustomerFromAccount methoddeletesa row from thecustomer_account_xref table. If a client calls the removeAccount method,then all rows for the specified accountId are removed from thecustomer_account_xref table.

The following methods get the account information:

• getAccountsOfCustomer

• getDetails

The AccountControllerBean sessionbeanhastwo get methods.The getAc-

countsOfCustomer methodreturnsall of the accountsof a given customerby

Page 5: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

SESSIONBEANS 1127

invoking thefindByCustomer methodof theAccountBean entity bean.Insteadof implementinga get methodfor every instancevariable, the AccountCon-

trollerBean has a getDetails method that returnsan object (AccountDe-tails) thatencapsulatestheentirestateof anAccountBean bean.Becauseit caninvoke a singlemethodto retrieve theentirestate,theclient avoidstheoverheadassociated with multiple remote calls.

CustomerContr ollerBeanBecauseit is theAccountControllerBean enterprisebeanthatmanagesthecus-tomer-accountrelationship,CustomerControllerBean is the simpler of thesetwo sessionbeans.A client createsa CustomerBean entity beanby invoking thecreateCustomer method of the CustomerControllerBean sessionbean.Toremoveacustomer, theclient callstheremoveCustomer method,whichnotonlyinvokes the remove method of CustomerBean, but also deletes from thecustomer_account_xref table all rows that identify the customer.

TheCustomerControllerBean sessionbeanhastwo methodsthatreturnmulti-ple customers:getCustomersOfAccount andgetCustomersOfLastName. Thesemethodscall the correspondingfinder methods—findbyAccountId andfind-ByLastName—of CustomerBean.

TxContr ollerBeanThe TxControllerBean sessionbeanhandlesbanktransactions.In addition toits get methods,getTxsOfAccount and getDetails, the TxControllerBean

bean has several methods that change the balances of the bank accounts:

• withdraw

• deposit

• makeCharge

• makePayment

• transferFunds

Thesemethodsaccessan AccountBean entity beanto verify the accounttypeandto setthenew balance.Thewithdraw anddeposit methodsarefor standardaccounts,whereasthe makeCharge andmakePayment methodsarefor accountsthat includea line of credit. If the type methodargumentdoesnot matchtheaccount,thesemethodsthrow an IllegalAccountTypeException. If a with-drawal were to result in a negative balance,the withdraw methodthrows anInsufficientFundsException. If a credit charge attempts to exceed the

Page 6: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1128 THE DUKE’S BANK APPLICATION

account’s credit line, the makeCharge methodthrows an InsufficientCredi-

tException.

The transferFunds methodalsochecksthe accounttype andnew balance;ifnecessary, it throws thesameexceptionsasthewithdraw andmakeCharge meth-ods.The transferFunds methodsubtractsfrom the balanceof oneAccount-

Bean instanceandaddsthe sameamount to anotherinstance.Becauseboth ofthesestepsmustcomplete,thetransferFunds methodhasa Required transac-tion attribute. If eitherstepfails, theentireoperationis rolled backandthebal-ances remain unchanged.

Entity BeansFor eachbusinessentity representedin our simplebank,theDuke’s Bankappli-cation has a matching entity bean:

• AccountBean

• CustomerBean

• TxBean

Thepurposeof thesebeansis to provide anobjectview of thesedatabasetables:account, customer, andtx. For eachcolumnin a table,thecorrespondingentitybeanhasan instancevariable.Becausethey usebean-managedpersistence,theentity beanscontaintheSQL statementsthataccessthetables.For example,thecreate methodof the CustomerBean entity beancalls the SQL INSERT com-mand.

Unlike the sessionbeans,the entity beansdo not validatemethodparameters(exceptfor theprimarykey parameterof ejbCreate). During thedesignphase,we decidedthat the sessionbeanswould checkthe parametersand throw theapplicationexceptions,suchasCustomerNotInAccountException andIllega-lAccountTypeException. Consequently, if some other application were toinclude theseentity beans,its sessionbeanswould also have to validate themethod parameters.

Becausetheentitybeansalwaysrun in thesameJavaVM astheirclientstheses-sion beans,for improved performance,the entity beansare codedwith localinterfaces.

Page 7: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

HELPER CLASSES 1129

Helper ClassesTheEJBJAR files includeseveralhelperclassesthatareusedby theenterprisebeans.Thesourcecodefor theseclassesis in the<INSTALL>/j2eetutorial14/examples/bank/src/com/sun/ebank/util/ directory. Table 32–3 brieflydescribes the helper classes.

Table 32–3 Helper Classes for the Application’s Enterprise Beans

Class Name Description

AccountDetails

Encapsulates the state of anAccountBean instance. Returned by thegetDetails methods ofAccountControllerBean andAccount-Bean.

CodedNames

Definesthestringsthatarethelogicalnamesin thecallsof thelookupmethod. (For example:java:comp/env/ejb/account). TheEJB-Getter class references these strings.

CustomerDetails

Encapsulates the state of aCustomerBean instance. Returned by thegetDetails methods ofCustomerControllerBean andCustom-erBean.

DBHelperProvides methods that generate the next primary keys (for example,getNextAccountId).

Debug

Has simple methods for printing a debugging message from an enter-prise bean. These messages appear on the standard output of the J2EE1.4ApplicationServerwhenit’srunwith the--verbose optionandinthe server log.

DomainUtilContains validation methods:getAccountTypes, checkAccount-Type, andisCreditAccount.

EJBGetterHas methods that locate (by invokinglookup) and return home inter-faces (for example,getAccountControllerHome).

TxDetailsEncapsulates the state of aTxBean instance. Returned by thegetDe-tails methods ofTxControllerBean andTxBean.

Page 8: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1130 THE DUKE’S BANK APPLICATION

Database TablesA databasetableof theDuke’s Bankapplicationmaybe categorizedby its pur-pose: representing business entities and holding the next primary key.

Tables Representing Business EntitiesFigure32–4shows relationshipsbetweenthedatabasetables.Thecustomer andaccount tableshaveamany-to-many relationship:A customermayhaveseveralbankaccounts,andeachaccountmaybeownedby morethanonecustomer. Thismany-to-many relationshipis implementedby the cross–referencetablenamedcustomer_account_xref. Theaccount andtx tableshave a one-to-many rela-tionship: A bank accountmay have many transactions,but each transactionrefers to a single account.

Figure32–4 Database Tables

Figure32–4makes useof severalabbreviations.PK standsfor primarykey, thevaluethatuniquelyidentifiesa row in a table.FK is anabbreviation for foreign

Page 9: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

PROTECTING THE ENTERPRISEBEANS 1131

key, which is the primary key of the relatedtable.Tx is short for transaction,such as a deposit or withdrawal.

Tables Tha t Hold the Ne xt Pr imar y KeyThese tables have the following names:

• next_account_id

• next_customer_id

• next_tx_id

Eachof thesetableshasa singlecolumnnamedid. Thevalueof id is thenextprimarykey thatis passedto thecreate methodof anentity bean.For example,beforeit createsa new AccountBean entity bean,theAccountControllerBean

sessionbean must obtain a unique key by invoking the getNextAccountId

methodof the DBHelper class.The getNextAccountId methodreadsthe id

from thenext_account_id table,incrementstheid valuein thetable,andthenreturns theid.

Protecting the Enter prise BeansIn the J2EEplatform,you protectan enterprisebeanby specifyingthe securityrolesthatcanaccessits methods.In theDuke’sBankapplication,youdefinetworoles—bankCustomer and bankAdmin—becausetwo categories of operationsare defined by the enterprise beans.

A userin the bankAdmin role will be allowed to perform administrative func-tions:creatingor removing anaccount,addinga customerto or removing a cus-tomerfrom anaccount,settingacreditline, andsettinganinitial balance.A userin the bankCustomer role will be allowed to deposit,withdraw, transferfunds,makechargesandpayments,andlist theaccount’s transactions.Noticethatthereis no overlap in functions that users in either role can perform.

Accessto thesefunctionsis restrictedto theappropriaterole by settingmethodpermissionson selectedmethodsof the CustomerControllerBean, Account-ControllerBean, and TxControllerBean enterprisebeans.For example, byallowing only usersin thebankAdmin role to accessthecreateAccount methodin theAccountControllerBean enterprisebean,youdeny usersin thebankCus-tomer role or any other role permission to create bank accounts.

Page 10: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1132 THE DUKE’S BANK APPLICATION

Application ClientSometimes,enterpriseapplicationsusea stand-aloneclient applicationfor han-dling tasks such as systemor application administration.For example, theDuke’s Bankapplicationusesa J2EEapplicationclient to administercustomersandaccounts.This capabilityis usefulin theeventthesitebecomesinaccessiblefor any reasonor a customerprefersto communicatethingssuchaschangestoaccount information by phone.

A J2EEapplicationclient is a standaloneprogramlaunchedfrom thecommandline or desktop;it accessesenterprisebeansrunning on the J2EEapplicationserver.

Theapplicationclientshown in Figure32–5handlesbasiccustomerandaccountadministrationfor the bankingapplicationthrougha Swing userinterface.Thebankadministratorcanperformany of thefollowing functionsby makingmenuselections.

Figure32–5 Application Client

Customer Administration

• View customer information

• Add a new customer to the database

• Update customer information

• Find customer ID

Page 11: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

THE CLASSESAND THEIR RELATIONSHIPS 1133

Account Administration

• Create a new account

• Add a new customer to an existing account

• View account information

• Remove an account from the database

Error and informationalmessagesappearin the left paneunderApplicationmessage watch:, and data is entered and displayed in the right pane.

The Classes and Their Rela tionshipsThe source code for the application client is in the <INSTALL>/

j2eetutorial14/examples/bank/src/com/sun/ebank/appclient/ direc-tory. The J2EE application client is divided into three classes:BankAdmin,EventHandle, andDataModel; the relationshipsamongtheclassesaredepictedin Figure32–6.

Page 12: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1134 THE DUKE’S BANK APPLICATION

Figure32–6 Relationships among Classes

BankAdmin builds the initial userinterface,createstheEventHandle object,andprovidesmethodsfor theEventHandle andDataModel objectsto call to updatethe user interface.

EventHandle listensfor button clicks by the user, takesactionbasedon whichbuttontheuserclicks, createstheDataModel object,callsmethodsin theData-Model objectto write datato andreaddatafrom theenterprisebeans,andcallsmethodsin theBankAdmin objectto updatetheuserinterfacewhenactionscom-plete.

DataModel retrieves datafrom the userinterface,performsdatachecks,writesvalid datato andreadsstoreddatafrom theunderlyingdatabase,andcallsmeth-odsin theBankAdmin objectto updatetheuserinterfacebasedon thesuccessofthe database read or write operation.

Page 13: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

BANKADMIN CLASS 1135

BankAdmin ClassTheBankAdmin class,which createstheuserinterface,is theclasswith themainmethod,andprovidesprotected methodsfor the otherBankAdmin applicationclasses to call.

main MethodThemain methodcreatesinstancesof theBankAdmin andEventHandle classes.Argumentspassedto the main methodareusedto initialize a locale,which ispassed to theBankAdmin constructor.

public static void main(String args[]) {String language, country;if(args.length == 1) {

language = new String(args[0]);currentLocale = new Locale(language, "");

} else if(args.length == 2) {language = new String(args[0]);country = new String(args[1]);currentLocale = new Locale(language, country);

} elsecurrentLocale = Locale.getDefault();frame = new BankAdmin(currentLocale);frame.setTitle(messages.getString("CustAndAccountAdmin"));WindowListener l = new WindowAdapter() {

public void windowClosing(WindowEvent e) {System.exit(0);

}};frame.addWindowListener(l);frame.pack();frame.setVisible(true);ehandle = new EventHandle(frame, messages);System.exit(0);}

}

Constr uctorTheBankAdmin constructorcreatesthe initial userinterface,which consistsof amenu bar and two panels.The menu bar containsthe customerand account

Page 14: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1136 THE DUKE’S BANK APPLICATION

menus,the left panelcontainsa messagearea,andthe right panelis a datadis-play or update area.

Class MethodsTheBankAdmin classprovidesmethodsthatotherobjectscall whenthey needtoupdate the user interface. These methods are as follows:

• clearMessages: Clearsthe applicationmessagesthat appearin the leftpanel

• resetPanelTwo: Resetstheright panelwhentheuserselectsOK to signalthe end of a data view or update operation

• createPanelTwoActLabels: Creates labels for account fields whenaccount information is either viewed or updated

• createActFields: Createsaccountfields when accountinformation iseither viewed or updated

• createPanelTwoCustLabels: Createslabels for customerfields whencustomer information is either viewed or updated

• createCustFields: Createscustomerfields whencustomerinformationis either viewed or updated

• addCustToActFields: Createslabelsandfieldsfor whenanaddcustomerto account operation is invoked

• makeRadioButtons: Makes radio buttonsfor selectingthe accounttypewhen a new account is created

• getDescription: Makestheradiobutton labelsthatdescribeeachavail-able account type

EventHandle ClassThe EventHandle classimplementsthe ActionListener interface,which pro-videsa methodinterfacefor handlingactionevents.Like all otherinterfacesintheJava programminglanguage,ActionListener definesa setof methods,butdoesnot implementtheir behavior. Instead,you provide the implementationsbecause they take application-specific actions.

Page 15: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

EVENTHANDLE CLASS 1137

Constr uctorThe constructorreceives an instanceof the ResourceBundle and BankAdmin

classesandassignsthemto its privateinstancevariablesothattheEventHandleobjecthasaccessto theapplicationclient’s localizedtext andcanupdatetheuserinterfaceas needed.Lastly, the constructorcalls the hookupEvents methodtocreate the inner classes to listen for and handle action events.

public EventHandle(BankAdmin frame, ResourceBundle messages) { this.frame = frame; this.messages = messages; this.dataModel = new DataModel(frame, messages); //Hook up action events hookupEvents();

}

actionP erformed MethodThe ActionListener interface has only one method, the actionPerformed

method.This methodhandlesaction eventsgeneratedby the BankAdmin userinterface when userscreatea new account.Specifically, it sets the accountdescriptionwhena bankadministratorselectsanaccounttype radiobuttonandsetsthecurrentbalanceto thebeginningbalancefor new accountswhena bankadministrator presses the Return key in the Beginning Balance field.

hookupEv ents MethodThehookupEvents methodusesinner classesto handlemenuandbutton pressevents.An inner classis a classnestedor definedinside anotherclass.Usinginner classesin this way modularizesthe code,making it easierto readand

Page 16: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1138 THE DUKE’S BANK APPLICATION

maintain.EventHandle inner classesmanagethe following applicationclientoperations:

• View customer information

• Create new customer

• Update customer information

• Find customer ID by last name

• View account information

• Create new account

• Add customer to account

• Remove account

• Clear data on Cancel button press

• Process data on OK button press

DataModel ClassTheDataModel classprovidesmethodsfor readingdatafrom thedatabase,writ-ing datato the database,retrieving datafrom the userinterface,and checkingthat data before it is written to the database.

Constr uctorTheconstructorreceives an instanceof theBankAdmin classandassignsit to itsprivateinstancevariablesothattheDataModel objectcandisplayerrormessagesin the user interface when its checkActData, checkCustData, or writeData

methoddetectserrors.It alsoreceives an instanceof theResourceBundle classandassignsit to its private instancevariableso that the DataModel objecthasaccess to the application client’s localized text.

BecausetheDataModel classinteractswith thedatabase,theconstructoralsohasthe codeto establishconnectionswith the remoteinterfacesfor the Customer-

Controller andAccountController enterprisebeans,andto usetheir remoteinterfacesto createinstancesof the CustomerController and AccountCon-

troller enterprise beans.

//Constructorpublic DataModel(BankAdmin frame, ResourceBundle messages) {

this.frame = frame;this.messages = messages;

Page 17: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

DATAMODEL CLASS 1139

//Look up and create CustomerController beantry {

CustomerControllerHome customerControllerHome =EJBGetter.getCustomerControllerHome();

customer = customerControllerHome.create();} catch (Exception namingException) {

namingException.printStackTrace();}

//Look up and create AccountController beantry {

AccountControllerHome accountControllerHome =EJBGetter.getAccountControllerHome();

account = accountControllerHome.create();} catch (Exception namingException) {

namingException.printStackTrace();}

}

MethodsThe getData methodretrieves datafrom the userinterfacetext fields andusestheString.trim methodto remove extra controlcharacterssuchasspacesandreturns.Its oneparameteris a JTextfield so that any instanceof the JText-

field class can be passed in for processing.

private String getData(JTextField component) { String text, trimmed; if(component.getText().length() > 0) {

text = component.getText();trimmed = text.trim();return trimmed;

} else {text = null;return text;

}}

The checkCustData method storescustomerdata retrieved by the getData

method,but first checksthedatato besureall requiredfieldshavedata,themid-dle initial is no longer thanonecharacter, and the stateis no longer than twocharacters.If everythingchecksout, thewriteData methodis called.If thereareerrors,they areprintedto theuserinterfacein theBankAdmin object.Thecheck-ActData method uses a similar model to check and store account data.

Page 18: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1140 THE DUKE’S BANK APPLICATION

ThecreateCustInf andcreateActInf methodsarecalledby theEventHandleclassto refreshthePanel2 displayin theeventof a view, update,or addactionevent.

Create Customer Information

• For aview or updateevent,thecreateCustInf methodgetsthecustomerinformationfor thespecifiedcustomerfrom thedatabaseandpassesit tothecreateCustFields methodin theBankAdmin class.A Booleanvari-ableis usedto determinewhetherthecreateCustFields methodshouldcreateread-onlyfields for a view event or writable fields for an updateevent.

• For a createevent, the createCustInf methodcalls the createCust-

Fields methodin theBankAdmin classwith null dataanda Booleanvari-able to create empty editable fields for the user to enter customer data.

Create Account Information

• For a view or updateevent, the createActInf methodgetsthe accountinformationfor thespecifiedaccountfrom thedatabaseandpassesit to thecreateActFields methodin theBankAdmin class.A Booleanvariableisusedto determinewhetherthe createActFields methodshouldcreateread-only fields for a view event or writable fields for an update event.

• For a createevent,thecreateActInf methodcallsthecreateActFieldsmethodin the BankAdmin classwith null dataanda Booleanvariabletocreate empty editable fields for the user to enter customer data.

• Addinga customerto anaccountor removing anaccounteventsoperatedirectly on the database without creating any user interface components.

Web ClientIn the Duke’s Bank application,the Web client is usedby customersto accessaccountinformation and perform operationson accounts.Table 32–7 lists thefunctionsthe client supports,the URLs usedto accessthe functions,and thecomponentsthatimplementthefunctions.Figure32–8showsanaccounthistoryscreen.

Page 19: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

WEB CLIENT 1141

The sourcecode for the web client is in the <INSTALL>/j2eetutorial14/

examples/bank/src/com/sun/ebank/web/ and<INSTALL>/j2eetutorial14/examples/bank/web/ directories.

Table 32–7 Web Client

Function URL Aliases JSP PagesJavaBeansComponents

Home page /main main.jsp

Log on or off theapplication

/logon

/logonError

/logoff

logon.jsp

logonError.jsp

logoff.jsp

List accounts /accountList accountList.jsp

List the history ofan account

/accountHist accountHist.jspAccountHistory-

Bean

Transfer fundsbetween accounts

/transferFunds

/transferAck

transferFunds.jsp

transferAck.jspTransferBean

Withdraw anddeposit funds

/atm

/atmAck

atm.jsp

atmAck.jspATMBean

Error handling /error error.jsp

Page 20: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1142 THE DUKE’S BANK APPLICATION

Figure32–8 Account History

Design Stra teg iesThemainjob of theJSPpagesin theDuke’s Bankapplicationis presentation.Inorderto achieve this, mostdynamicprocessingtasksaredelegatedto enterprisebeans, custom tags, and JavaBeans components.

In the Duke’s Bank application,the JSPpagesuseenterprisebeansto handleinteractionswith the database.In addition, the JSPpagesrely on JavaBeanscomponentsfor interactionswith theenterprisebeans.In theDuke’s Bookstoreapplication,presentedin chapters11 to 15, the BookDB JavaBeanscomponentactedasa front endto a databaseor asa facadeto the interfaceprovidedby an

Page 21: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

WEB CLIENT LIFE CYCLE 1143

enterprisebean.In the Duke’s Bank application,TransferBean playsthe samerole. However, theotherJavaBeanscomponentshave muchricher functionality.ATMBean invokes enterprisebeanmethodsand setsacknowledgementstringsaccording to customer input, and AccountHistoryBean massagesthe datareturnedfrom the enterprisebeansin order to presentthe view of the datarequired by the customer.

The Web client usesa templatemechanismimplementedby customtags(dis-cussedin A TemplateTag Library, page636)to maintaina commonlook acrossall the JSP pages. The template mechanism consists of three components:

• template.jsp determinesthestructureof eachscreen.It usestheinserttag to compose a screen from subcomponents.

• screendefinitions.jspf defines the subcomponentsused by eachscreen.All screenshave thesamebanner, but differenttitle andbodycon-tent (specified by the JSP Pages column in Table 32–7).

• Dispatcher, aservlet,processesrequestsandforwardsto template.jsp.

Finally, theWeb clientuseslogic tagsfrom theJSTLcore taglibrary to performflow control andthe JSTLfmt tag library to localizemessagesandformat cur-rency.

Web Client Life Cy cle

Initializing the Client ComponentsResponsibilityfor managingthe enterprisebeansusedby the Web client restswith the BeanManager class.It createscustomer, account,andtransactioncon-troller enterprise beans and provides methods for retrieving the beans.

Wheninstantiated,BeanManager retrieves thehomeinterfacefor eachbeanfromthehelperclassEJBGetter andcreatesaninstanceby calling thecreate methodof the homeinterface.This is a session-level function: BeanManager is createdand stored as a session attribute.

public class BeanManager {private CustomerController custctl;private AccountController acctctl;private TxController txctl;public BeanManager() {

if (custctl == null) {try {

Page 22: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1144 THE DUKE’S BANK APPLICATION

CustomerControllerHome home =EJBGetter.getCustomerControllerHome();

custctl = home.create();} catch (RemoteException ex) {

Debug.print("Couldn’t create customer bean." +ex.getMessage());

} catch (CreateException ex) {Debug.print("Couldn’t create customer bean." +

ex.getMessage());} catch (NamingException ex) {

Debug.print("Unable to lookup home: " +CodedNames.CUSTOMER_CONTROLLER_EJBHOME +ex.getMessage());

}}public CustomerController getCustomerController() {

return custctl;}...

}

Request Pr ocessingAll requestsfor the URLs listed in Table32–7 aremappedto thedispatcherWeb component, which is implemented by theDispatcher servlet:

public class Dispatcher extends HttpServlet {public void doPost(HttpServletRequest request,

HttpServletResponse response) {...String selectedScreen = request.getServletPath();...if (selectedScreen.equals("/accountHist")) {

...} else if (selectedScreen.equals("/transferAck")) {

String fromAccountId =request.getParameter("fromAccountId");

String toAccountId =request.getParameter("toAccountId");

if ( (fromAccountId == null) || (toAccountId == null)) {request.setAttribute("errorMessage",

messages.getString("AccountError"));try {

request.getRequestDispatcher("/error.jsp").forward(request, response);

} catch(Exception ex) {}

Page 23: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

WEB CLIENT LIFE CYCLE 1145

} else {TransferBean transferBean = new TransferBean();request.setAttribute("transferBean",

transferBean);try {

transferBean.setMessages(messages);transferBean.setFromAccountId(fromAccountId);transferBean.setToAccountId(toAccountId);transferBean.setBeanManager(beanManager);transferBean.setTransferAmount(new

BigDecimal(request.getParameter("transferAmount")));

String errorMessage = transferBean.doTx();if (errorMessage != null) {

request.setAttribute("errorMessage",errorMessage);

try {request.getRequestDispatcher(

"/error.jsp").forward(request, response);} catch(Exception ex) {}

}} catch (NumberFormatException e) {

request.setAttribute("errorMessage",messages.getString("AmountError"));

try {request.getRequestDispatcher(

"/error.jsp").forward(request, response);} catch(Exception ex) {}

}}...try {

request.getRequestDispatcher("/template/template.jsp").forward(request, response);

} catch(Exception e) {}

}}

When a request is delivered,Dispatcher does the following:

1. Retrieves and saves the incoming requestURL in the requestattributeselectedScreen. ThisisdonebecausetheURL will bemodifiedwhentherequest is later forwarded to the application’s template page.

2. Creates a JavaBeans component and stores the bean as a request attribute.

Page 24: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1146 THE DUKE’S BANK APPLICATION

3. Parsesandvalidatestherequestparameters.If aparameteris invalid,Dis-patcher mayresettherequestaliasto anerrorpage.Otherwise,it initial-izes the JavaBeans component.

4. CallsthedoTx methodof theJavaBeanscomponent.Thismethodretrievesdatafrom theenterprisebeansandprocessesthedataaccordingto optionsspecified by the customer.

5. Forwards the request totemplate.jsp.

As mentionedearlier, template.jsp generatesthe responseby including theresponsesfrom subcomponents.If the requestis a GET, thebodysubcomponentusually retrieves data from the enterprisebeandirectly; otherwiseit retrievesdata from the JavaBeans component initialized byDispatcher.

Figure32–9 depicts the interaction between these components.

Figure32–9 Web Component Interaction

Page 25: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

PROTECTING THE WEB RESOURCES 1147

Protecting the W eb Resour cesIn the J2EEplatform, a Web resourceis protectedfrom anonymousaccessbyspecifying which security roles can accessthe resource.The Web containerguaranteesthatonly certainusersactingin thoserolescanaccesstheresource.Inorder for the Web containerto enforcethe securityconstraint,the applicationmust specify a meansfor usersto identify themselves and the Web containermust support mapping a role to a user.

In theDuke’s BankWeb client, you restrictall of theURLs listedin Table32–7to the security role bankCustomer. The applicationrequiresusersto identifythemselves via the form-basedlogin mechanism.When a customertries toaccessaWebclientURL, andhasnotbeenauthenticated,theWeb containerdis-plays the JSPpagelogon.jsp. This pagecontainsa form that requiresa cus-tomer to enter an identifier and password.

<form action="j_security_check" method=post><table><tr>

<td align="center" ><table border="0"><tr><td><b><fmt:message key="CustomerId"/></b></td><td>

<input type="text" size="15" name="j_username"></td></tr><tr><td><b><fmt:message key="Password"/></b></td><td>

<input type="password" size="15" name="j_password"></td>...

</form>

Notethattheactioninvoked by theform, j_security_check, is specifiedby theJava Servlet specification,as are the request parametersj_username andj_password. TheWeb containerretrieves this information,mapsit to a securityrole, andverifiesthat the role matchesthat specifiedin the securityconstraint.Note that in orderfor theWeb containerto checkthevalidity of theauthentica-tion information and perform the mapping,you must perform thesetwo stepswhen you deploy the application:

1. Add the customer’s group,ID, andpassword to the default realmof thecontainer using the Admin Console.

Page 26: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1148 THE DUKE’S BANK APPLICATION

2. Map the bankCustomer role to the customeror customer’s group indeploytool.

Oncethe customerhasbeenauthenticated,the identifier provided by the cus-tomer is usedas a key to identify the customer’s accounts.The identifier isretrieved from the request using the following expression:

${pageContext.request.userPrincipal.name}

Inter nationalizationThe J2EEapplicationclient and Web client distributed with the Duke’s Bankapplicationareinternationalized.All stringsthatappearin theuserinterfacesareretrieved from resourcebundles.TheadministrationclientusesresourcebundlesnamedAdminMessages_*.properties. The Web client usesresourcebundlesnamedWebMessages_*.properties. Both clients are distributed with Englishand Spanish resource bundles.

The applicationclient retrieves localeinformationfrom the commandline. Forexample, to use the Spanish resource bundle, invoke the application like this:

appclient -client DukesBankAppClient.jar es

The administrationclient classBankAdmin createsa ResourceBundle with alocale created from the command-line arguments:

//Constructorpublic BankAdmin(Locale currentLocale) {

//Internationalization setupmessages = ResourceBundle.getBundle("AdminMessages",

currentLocale);

The Web client Dispatcher componentretrieves the locale (set by a browserlanguagepreference)from therequest,openstheresourcebundle,andthensavesthe bundle as a session attribute:

ResourceBundle messages = (ResourceBundle)session.getAttribute("messages");if (messages == null) {

Locale locale=request.getLocale();

Page 27: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

BUILDING , PACKAGING, DEPLOYING, AND RUNNING THE APPLICATION 1149

messages = ResourceBundle.getBundle("WebMessages",locale);

session.setAttribute("messages", messages);}

The Web client’s JavaBeanscomponentsaccesslocalized messagesusingmessages.getString(“key”);.

TheWeb client’s JSPpagesusetheJSTLfmt:message tagsto retrieve localizedmessages.You setthe localizationcontext of theJSTLfmt tag library asa con-text parameter when you package the Web client withdeploytool.

For example,hereis how accountHist.jsp generatestheheadingsfor thetrans-actions table:

<td><center><b><fmt:messagekey="TxDate"/></b></center></td>

<td><center><b><fmt:messagekey="TxDescription"/></center></b></td>

<td><center><b><fmt:messagekey="TxAmount"/></b></center></td>

<td><center><b><fmt:messagekey="TxRunningBalance"/></b></center></td>

Building, P ackag ing, Deplo ying, andRunning the Application

To build theDuke’s Bankapplication,you musthave downloadedandunzippedthe tutorial bundleasdescribedin About the Examples(pagexxix). Whenyouinstall the bundle, the Duke’s Bank application files are located in the<INSTALL>/j2eetutorial14/examples/bank/ directory:

/bank

/provided-jars - packaged Web client and J2EE applicationcontaining the enterprise beans and application client

/sql - database scripts/src

/com - component classes/sun/ebank/appclient

/sun/ebank/ejb

/sun/ebank/util

Page 28: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1150 THE DUKE’S BANK APPLICATION

/sun/ebank/web

/web - JSP pages, images

After you compile the source code, the resulting files will reside in the<INSTALL>/j2eetutorial14/examples/bank/build/ directory.

Setting Up the Ser versBeforeyou canpackage,deploy, andrun theexample,you mustfirst setup thePointBasedatabaseserver with customerand account data, and add someresources to the J2EE 1.4 Application Server.

Creating the Bank Da tabaseYou createandenterdatainto theappropriatetablessothat theenterprisebeanshave somethingto readfrom andwrite to the database.To createandpopulatethe database tables:

1. Start the PointBase database server.

2. In a terminal window or commandprompt, go to the <INSTALL>/

j2eetutorial14/examples/bank/ directory and executethe commandasant create-db_common. This taskinvokes the PointBaseconsoletoollibrary to executethe SQL containedin <INSTALL>/j2eetutorial14/

examples/bank/sql/bank.sql. The SQL statementsin this file deleteany existing tables,createnew tables,andinsertdata.The first time thescriptis runthetablesdon’t exist, soyouwill seeSQLerrors.You canjustignore them.

Creating the JDBC Da ta Sour ceThe Duke’s Bank enterprisebeansreferencethe databasewith the JNDI namejdbc/BankDB. That JNDI namemust be mappedto a JDBC datasourcein theJ2EE1.4ApplicationServer. Youcreatethedatasourcewith theAdmin Consolefollowing theproceduresdescribedin DefiningaDataSourcein theJ2EEAppli-cationServer (page901).WhenyoucreatetheJDBCdatasource,nameit jdbc/BankDB and map it to PointBasePool.

Page 29: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

COMPILING THE DUKE’S BANK APPLICATION CODE 1151

Adding User s and Gr oups to the File RealmTo enabletheJ2EE1.4 ApplicationServer to determinewhich userscanaccessenterprisebeanmethodsandresourcesin theWeb client,addusersandgroupstotheserver’sfile securityrealmwith theAdmin Consolefollowing theproceduresdescribedin ManagingUsers(page913). Add the usersand groupslisted inTable 32–10.

Compiling the Duk e’s Bank Applica tionCodeTo compile the enterprisebeans,applicationclient, and Web client, go to the<INSTALL>/j2eetutorial14/examples/bank/ directory of the tutorial distri-bution and execute the commandasant compile.

Packag ing and Deplo ying the Duk e’sBank Applica tionThe instructionsthat follow for packaginganddeploying Duke’s Bank assumethat you are familiar with the deploytool proceduresfor packagingenterprisebeans,applicationclients,andWeb applicationsdescribedin previous chaptersof thetutorial. If afterfollowing theseproceduresyou have troubledeploying orrunningtheapplication,youcanusetheEAR andWAR providedin <INSTALL>/

j2eetutorial14/examples/bank/provided-jars/ to run the example.

Table 32–10 Duke’s Bank Users and Groups

User Password Group

200 j2ee bankCustomer

bankadmin j2ee bankAdmin

Page 30: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1152 THE DUKE’S BANK APPLICATION

Packag ing the Enter prise Beans1. InvoketheEnterpriseBeanwizardfor eachentitybeanin Table32–11.For

each bean, selectjava.lang.String as the Primary Key Class.

The first time you invoke the wizard,createan EJB JAR modulenamedDukesBankEJBJAR in <INSTALL>/j2eetutorial14/examples/bank/

andaddtheejb andutil packagesunder<INSTALL>/j2eetutorial14/examples/bank/build/com/sun/ebank/ to the JAR.

2. For eachentitybean,addaresourcereferenceto adatasourcewith CodedNamejdbc/BankDB. Set the Sun-specificJNDI nameto jdbc/BankDB.SinceyouhavealreadyaddedtheJDBCresourceto theapplicationserver,you should select the name from the drop-down menu.

3. For eachentity bean,set the transactionattributes for all methodstoRequired,exceptfor themethodslisted in Table32–12,which shouldbeset to Not Supported:

Table 32–11 Entity Beans

Entity BeanHomeInterface

LocalInterface Implementation Class

AccountBean AccountHome Account AccountBean

CustomerBean CustomerHome Customer CustomerBean

TxBean TxHome Tx TxBean

Table 32–12 Transaction Attribute Settings

Entity Bean Tx Not Supported Methods

AccountBean

getCreditLine

findByCustomerId

findByPrimaryKey

CustomerBean

remove

findByLastName

findByPrimaryKey

Page 31: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

PACKAGING AND DEPLOYING THE DUKE’S BANK APPLICATION 1153

4. InvoketheEnterpriseBeanWizardfor eachof thestatefulsessionbeansinTable 32–14.

5. For eachsessionbean,add a resourcereferenceto a datasourcewithCodedNamejdbc/BankDB. Set the Sun-specificJNDI nameto jdbc/

BankDB. Sinceyou have alreadyaddedtheJDBCresourceto theapplica-tion server, you should select the name from the drop-down menu.

6. Add EJB referencesfrom the sessionbeansto the entity beanslisted inTable 32–14.

TxBean

remove

findByAccountId

findByPrimaryKey

Table 32–13 Stateful Session Beans

Session Bean Home InterfaceRemoteInterface Implementation Class

AccountCon-

trollerBean

AccountCon-

trollerHome

AccountCon-

troller

AccountController-

Bean

CustomerCon-

trollerBean

CustomerCon-

trollerHome

CustomerCon-

troller

CustomerController-

Bean

TxController-

Bean

TxController-

HomeTxController TxBean

Table 32–14 EJB References to Entity Beans

Session Bean Coded Name JNDI Name of Entity Bean

AccountControllerBeanejb/account

ejb/customer

AccountBean

CustomerBean

CustomerControllerBean ejb/customer CustomerBean

Table 32–12 Transaction Attribute Settings (Continued)

Entity Bean Tx Not Supported Methods

Page 32: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1154 THE DUKE’S BANK APPLICATION

7. Add the security settings.

a. DukesBankEJBJAR - In the Securitytab,addthe rolesbankAdmin andbankCustomer.

b. AccountControllerBean - In theSecuritytab,restrictaccessto usersin thebankAdmin securityrole for the methodssetBalance, remove-Customer, setCreditLine, setDescription, removeAccount, cre-

ateAccount, addCustomerToAccount, setBeginBalance, andsetType. In theGeneraltab,selectSun-specificSettings→IOR. In theAs Context frame, set Required totrue.

c. CustomerControllerBean - In theSecuritytab,restrictaccessto usersin the bankAdmin securityrole for the methodsgetCustomersOfAc-count, createCustomer, getCustomersOfLastName, setName,removeCustomer, andsetAddress. In theGeneraltab,selectSun-spe-cific Settings→IOR. In the As Context frame, set Required totrue.

d. TxControllerBean - In theSecuritytab,restrictaccessto usersin thebankCustomer securityrole for themethodsgetTxsOfAccount, make-Charge, deposit, transferFunds, withdraw, andmakePayment.

8. Save the module.

Packag ing the Applica tion Client1. Invoke the Application Client wizard.

a. Create an application client module named DukesBankACJAR in<INSTALL>/j2eetutorial14/examples/bank/.

b. Add theappclient, util, andejb/exception packagesandtheejb/*/*Controller* home and local or remote interfaces(AccountCon-troller, AccountControllerHome, CustomerController, Customer-ControllerHome, TxController, TxControllerHome) under<INSTALL>/j2eetutorial14/examples/bank/build/com/sun/

ebank to the JAR.

c. Selectappclient.BankAdmin as the application client main class.

TxControllerBeanejb/account

ejb/tx

AccountBean

TxBean

Table 32–14 EJB References to Entity Beans (Continued)

Session Bean Coded Name JNDI Name of Entity Bean

Page 33: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

PACKAGING AND DEPLOYING THE DUKE’S BANK APPLICATION 1155

2. Add EJB references to thse session beans listed in Table 32–15.

3. Save the module.

Packag ing and Deplo ying the W eb Client1. Createa Dispatcher servletWeb componentusingtheWeb Component

wizard.Createanew Web modulecontainingthecomponentDukesBank-WAR in <INSTALL>/j2eetutorial14/examples/bank/.

2. Add content to the Web module.

a. Add theweb, util, andejb/exception packagesandtheejb/*/*Con-troller* home and local or remote interfaces(AccountController,AccountControllerHome, CustomerController, CustomerControl-lerHome, TxController, TxControllerHome) under <INSTALL>/

j2eetutorial14/examples/bank/build/com/sun/ebank to themod-ule.

b. Add thetemplate directory, all theJSPpages,theWebMessages*.pro-properties files and tutorial-template.tld under <INSTALL>/j2eetutorial14/examples/bank/build/ to the module.

c. In theWeb modulecontentseditor, dragthefilesWebMessages*.prop-erties from the context root toWEB-INF/classes.

3. Set the context root to/bank.

4. Add the /accountHist, /accountList, /atm, /atmAck, /main, /trans-ferAck, /transferFunds, and/logoff aliasesto theDispatcher compo-nent.

Table 32–15 EJB References to Session Beans

Coded Name JNDI Name of Session Bean

ejb/accountController AccountControllerBean

ejb/customerController CustomerControllerBean

Page 34: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1156 THE DUKE’S BANK APPLICATION

5. Add EJB references to the session beans listed in Table 32–16:

6. Add a JSPpropertygroupnamedbank. Thepropertygroupappliesto theURL pattern*.jsp. Add the include prelude/template/prelude.jspf.

7. Add a context parameternamedjavax.servlet.jsp.jstl.fmt.local-izationContext and valueWebMessages.

8. Add a security constraint.

a. SelectFormBasedastheUserAuthenticationMethod.Theauthentica-tion settingsarefile for theRealmName,/logon.jsp for theLoginPage, and/logonError.jsp for the Error Page.

b. Add asecurityconstraintandawebresourcecollection.Usethedefaultnames provided bydeploytool.

c. Add the URL Patterns/main, /accountList, /accountHist, /atm, /atmAck, /transferAck, and/transferFunds to thewebresourcecol-lection.

d. Select the GET and POST HTTP methods.

e. Add the security rolebankCustomer.

9. Map thebankCustomer role to thebankCustomer group.

10.Save the module.

11.Deploy the module.

Packag ing and Deplo ying the Applica tion1. Create a J2EE application named DukesBankApp in <INSTALL>/

j2eetutorial14/examples/bank/.

2. Add theDukesBankACJAR application client module toDukesBankApp.

Table 32–16 EJB References to Session Beans

Coded Name JNDI Name of Session Bean

ejb/accountController AccountControllerBean

ejb/customerController CustomerControllerBean

ejb/txController TxControllerBean

Page 35: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

PACKAGING AND DEPLOYING THE DUKE’S BANK APPLICATION 1157

3. Add theDukesBankEJBJAR EJB module toDukesBankApp.

4. Map thebankCustomer role to thebankCustomer group.

5. Map thebankAdmin role to thebankAdmin group.

6. Save the application.

7. Deploy the application.In the Deploy DukesBankApp dialog, selecttheReturn Client Jar checkbox.

After you have packagedall the modules, deploytool should look likeFigure32–17.

Figure32–17 Duke’s Bank Modules and Components

Page 36: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1158 THE DUKE’S BANK APPLICATION

Reviewing JNDI NamesWith DukesBankApp selected,click the JNDI Namestab. The JNDI Namecol-umn is shown in Figure32–18.The ordermay be a little differentin your ownenvironment.

Figure32–18 Duke’s Bank JNDI Names

Page 37: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

REVIEWING JNDI NAMES 1159

A JNDI nameis thenametheJ2EEserver usesto look up enterprisebeansandresources.Whenyou look up anenterprisebean,you supplystatementssimilarto those shown in the following code.

try {customerControllerHome =

EJBGetter.getCustomerControllerHome();customer = customerControllerHome.create();

} catch (Exception namingException) {namingException.printStackTrace();

}

public static CustomerControllerHomegetCustomerControllerHome() throws NamingException {InitialContext initial = new InitialContext();Object objref = initial.lookup(

CodedNames.CUSTOMER_CONTROLLER_EJBHOME);

Thelookuptakesplacein thethird line of code,in which thegetCustomerCon-trollerHome methodof com.sun.ebank.utilEJBGetter is called.EJBGetteris a utility class that retrieves a coded JNDI name fromcom.sun.ebank.util.CodedNames.

In this example,theapplicationclient is looking up thecodednamefor theCus-tomerController remoteinterface.BankAdmin (the displaynamefor the mainclassof the applicationclient) referencesejb/customerController, which isthe codednamedefinedin CodedNames for the CustomerController remoteinterface.

TheJNDI nameis storedin theJ2EEapplicationdeploymentdescriptor, andtheJ2EE server uses it to look up the CustomerControllerBean bean. InFigure32–18 you seethat CustomerControllerBean is mappedto the sameJNDI nameas is ejb/customerController. It doesnot matterwhat the JNDInameis, aslongasit is thesamenamefor theremoteinterfacelookupasyouusefor its correspondingbean.So,looking at thetable,you cansaythattheapplica-tion client (BankAdmin) looks up the CustomerController remoteinterface,which usesthe JNDI nameof CustomerControllerBean, andthe J2EEserverusestheCustomerControllerBean JNDI nameto find the correspondingCus-tomerControllerBean object.

Theotherrows in thetablehave themappingsfor theotherenterprisebeans.Allof thesebeansarestoredin theJAR file you addedto theJ2EEapplicationdur-ing assembly. Their implementationshave codednamesfor looking up eitherother enterprise beans or the database driver.

Page 38: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1160 THE DUKE’S BANK APPLICATION

Running the Clients

Running the J2EE Applica tion ClientTo run the J2EE application client:

1. In a terminal window, go to <INSTALL>/j2eetutorial14/examples/

bank/.

2. To run the English version of the client, execute the following command:appclient -client DukesBankAppClient.jar

TheDukesBankAppClient.jar parameteris thenameof theJ2EEappli-cation client JAR file returned when you deployedDukesBankApp.

3. To run the Spanish version, include thees language code:appclient -client DukesBankAppClient.jar es

4. At the login prompts,type in bankadmin for theusernameandj2ee forthe password. The next thing you shouldseeis the applicationshown inFigure32–19.

Figure32–19 BankAdmin Application Client

Page 39: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

RUNNING THE WEB CLIENT 1161

Running the W eb ClientTo run the Web client:

1. Open the bank URL, http://localhost:8080/bank/main, in a Webbrowser. To seethe Spanishversionof the application,setyour browserlanguage preference to any Spanish dialect.

2. Theapplicationwill displaythelogin page.Enter200 for thecustomerIDandj2ee for the password. Click Submit.

3. Selectan applicationfunction: Account List, TransferFunds,ATM, orLogoff. Onceyou have a list of accounts,you cangetanaccounthistoryby selecting an account link.

Note: Thefirst time youselectanew page,particularlyacomplicatedpagelikeanaccounthistory, it takessometime to displaybecausetheJ2EEApplicationServermust translate the page into a servlet class and compile and load the class.

If you select Account List, you will see the screen shown in Figure32–20.

Figure32–20 Account List

Page 40: The Duke’s Bank Applicationcation. Duke’s Bank has two clients: a J2EE application client used by adminis-trators to manage customers and accounts, and a Web client used by customers

1162 THE DUKE’S BANK APPLICATION