Tải bản đầy đủ - 0 (trang)
Chapter 8. Testing Servlets Using WSAD

Chapter 8. Testing Servlets Using WSAD

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

8.1EdittheWebDeploymentDescriptor

TheWebapplicationinChapter7containsabusinessmodel,alist-detail

viewofthemodel,andacontrollerservletthatupdatesthemodel.In

ordertoexecutethisWebapplication,wemustfirstdescribeittothe

applicationserversoitknowswhat'sintheapplication,whatresourcesit

uses,andhowtoinvokeit.That'stheroleoftheJ2EEWebapplication

deploymentdescriptor.TheWebapplicationdeploymentdescriptorisan

XMLfilecalledweb.xmlintheWEB-INFfolderofaWebapplication.To

opentheWebdeploymentdescriptoreditorasshowninFigure8.1,either

double-clicktheweb.xmlfiledirectlyordouble-clickWebDeployment

Descriptor(whichappearsrightundertheWebprojectname)fromthe

J2EEnavigatorview.



Figure8.1.Webdeploymentdescriptoreditorforservlet

example.



Thiseditordisplaysinformationintheweb.xmlfilecombinedwith

informationintheWebSpherebindingsfile(ibm-web-bnd.xmi)and

WebSphereextensionsfile(ibm-web-ext.xmi).TheseXMLfiles

containextensionstothedeploymentdescriptorthataresupportedby

IBMWAS5.0.Youcaneditallthreefilesasasinglelogicalunitwiththe

deploymentdescriptoreditor,whichorganizestheinformationinthe

deploymentdescriptorintoanumberoftabbedpages.Thefollowing

paragraphsprovideanoverviewoftheeditortabs,includingfurther

informationonsettingsrequiredforthesampleapplication.Fora

completedescriptionoftheeditor,seetheWSADHelp.

TheOverviewtabprovidesthemostcommonlyupdatedinformation,

givingataglancetheWebapplicationname,description,theservlets

containedintheapplication,thewelcomeanderrorpages,etc.Italso

showstheenterpriseapplicationsthatusethisWebapplication.Seethe

nextsectionfordetailsonhowtoaddaWebapplicationtoanenterprise

applicationsoaJ2EEWebapplicationservercanexecuteit.

TheServletstabprovidesadditionaldetailsabouttheservletsintheWeb

application.Figure8.2showstheservletspagewiththe

BrowseEmployeesservletselected.Noticethatthedetailsshownforthe

servletarethesameinformationthatweenteredinthenewservlet

wizard.Youcaneditthatinformationhereifneeded.Notethatyoucan

expandandcontractthesubsectionsoftheformtodisplayorhide

informationasneeded.Usethisfeaturetohidedeploymentinformation

thatyoudon'tneedtochange.Theeditorrememberstheexpansionstate

ofeachsectionsotheyaredisplayedthesamewaythenexttimethe

editorisopened.



Figure8.2.Webdeploymentdescriptoreditor.



TheFilterstabattachesfilterstoaservlet.You'llrememberfromChapter

6thatyoucanattachfilterstoservletsinordertoprovidefurther

processingontheirinputoroutput.

TheListenerstabisforaddingservletcontextorHTTPsessionlisteners

thatarenotifiedwhentheservletcontextorHTTPsessionisinitialized,

changed,ordestroyed.Youcanuselistenerstohandlechangeeventsin

theservletcontextorHTTPsessioninsteadofhavingtodistributeor

duplicatechange-eventmanagementcodeinmanydifferentservlets.

TheSecuritytabisformanagingaccesscontroltoWebapplication

resources.UsetheSecurityRolessubtabtodefinerolesplayedbyusers

ofyourapplication,thenswitchtotheSecurityConstraintssubtabto

createspecificaccesscontrolorsecurityconstraints.Eachsecurity

constraintcanhaveanumberofWebresourcecollectionsthatspecify

thepermittedHTTPmethodsandURLpatternsforidentifyingthe

resourcesinthecollection.Thesecurityconstraintalsospecifieswhich

securityrolesareabletoaccesstheresourcesidentifiedbytheWeb

resourcecollection.Wewillexaminethismoreinalaterchapter.

TheEnvironmenttabdefinesvariablesavailabletoallservletsintheWeb



application.Usethistabtodefineconstantsusedinyourservlets,but

thatmayneedtobecustomizedbyusersoradministratorsinsteadof

beingfixedinthecodeitself.

TheReferencestabspecifiesotherresourcesreferencedbythisWeb

applicationincludingEJBs,JDBCdatasources,andJSPtaglibraries.

We'llbelookingattheReferencestabinmoredetailinsubsequent

chapters,butinthischapter,wedoneedtoconfiguretheJDBCdata

sourcethatisusedtoaccesstheemployeesdatabase.Figure8.3shows

theResourcesubtab.CreatearesourcereferencebypressingAddatthe

bottomoftheresourcereferenceslist.Namethenewreferenceasshown

inFigure8.3,orusethenameyouspecifiedforthedatasourcenamein

theapplication.propertiesfile:



com.wsbook.servletexample.mapping.datasource.name=java:comp/env



Figure8.3.ConfiguringtheJDBCresource.



Resourcesspecifiedinthiswayareplacedinthejava:comp/env/

namespace.Thatis,theyarelookedupintheapplicationusingnames

likejava:comp/env/jdbc/EJPBOOKinsteadoftheirspecific,global

JavaNamingandDirectoryInterface(JNDI)names.TheglobalJNDI

nameisspecifiedundertheWebSphereBindingsintheJNDINamefield

ontheReferencespage.

Forourdatabaseaccess,specifythenameusedbytheWebapplication

servertolookupthedatasource.Figure8.3usesjdbc/EJPBOOKasthe

nonlocalJNDInametoindicatetheresourceisaJDBCdatasource,and

therestofthenamecorrespondstothesampleemployeedatabase.You

canuseanyJNDInameyouwantaslongasitdoesn'tconflictwithsome

otherreferencenamefortheservlet;however,itisusefultousenames

thateasilyidentifytheaccessedresource.

YoucanusethenonlocalJNDInamedirectlyintheapplication,

eliminatingtheneedtospecifyaresourcereferenceintheWeb

applicationdeploymentdescriptor.However,thiscancreateproblems

whenthesameapplicationisdeployedonmorethanoneWeb

applicationserver.Itmaybenecessaryfortheapplicationtoaccessits

resourcesfromadifferentJNDIserverwithadifferentname.Bydefining

resourcereferencesintheWebdeploymentdescriptor,theresource

java:comp/env/referencecanbemappedtoadifferentJDBCURI

withouthavingtochangetheservletsourcecode.Inaddition,bycreating

alocalresourcereference,theapplicationisinformingtheapplication

serverthatitusesthisresource.Theapplicationserverwillalterthe

classpath,aswellastakeotherstepstosupportthisusage.

WelcomeanderrorpagesfallunderthePagestab.Welcomepages

specifythedefaultpagesusedwhenaURLreferstoafoldercontaininga

collectionofresources.Thedefaultisbasedontheordergiveninthelist,

withtheresourcesatthetopselectedfirst,ifmorethanonewelcome

pageexistsinthefolder.UseerrorpagestospecifyaURLforapage

thatistobedisplayedinsteadofadefaultpagewhenaparticularHTTP

erroroccurs.Forexample,specifypageNotFound.htmlforerrorcode404

toprovideanHTMLpagetodisplaywhenaresourcedoesnotexist.



UsetheParameterstabtoadddefaultparametervaluesintotheWeb

applicationcontext.Theseparametersareavailablethroughthe

applicationcontext.UsetheMIMEtabtospecifycustomMIMEtypesfor

fileextensions.TheseMIMEtypeswillbeautomaticallyincludedinHTTP

headerswhentheWebapplicationserveraccessesaresourcewiththe

customextension.BrowserstypicallyusetheMIMEtypeheader

informationtoknowhowtodisplaytheresource.

TheExtensionstabspecifiesWebapplicationextensionssupportedby

WAS.Oneusefulextensionisthedefaulterrorpage.Usethisparameter

toenterorselectthedefaulterrorpagedisplayedonanyHTTPerror

otherthanthoseoverriddeninthePagestab.

TheMIMEfiltersgroupisanalternativetoservletfilters.MIMEfilters

eithertransformthecontentsofanHTTPrequestorresponseormodify

HTTPheaders.MIMEfiltersforwardHTTPresponseswithaspecified

MIMEtypetooneormoreservletswheretheresponsecanbetranslated

tosomeotherMIMEtype.Otherextensionsarecoveredthroughoutthe

bookasneeded.

YoucaneditthedeploymentdescriptorXMLsourcedirectlyusingthe

sourcepage.Notethatthesourcepageonlydisplaysthecontentsofthe

web.xmlfile,whichcontainstheJ2EE1.3standarddeployment

descriptioninformation.ToseeoreditthesourcefortheWebSphere

bindingsandextensions,opentheibm-web-bnd.xmioribm-webext.xmiintheWEB-INFfolderusingtheXMLordefaulttexteditor.

Changestothesourcepageareimmediatelyreflectedintheotherdesign

pagesandviceversa.



8.1.1DeployingtoanEnterpriseApplication

NowthattheWebapplicationisdescribedinitsdeploymentdescriptor,

wearereadytosendittoanapplicationserverandstarttesting.Aswe

describedinChapter4,J2EE1.3applicationserversrunenterprise

applicationsdescribedbyenterpriseapplicationdeploymentdescriptors.

InordertodeployaJ2EE1.3Webapplication,itmustfirstbeaddedto



anenterpriseapplication,whichisthendeployedtoanapplicationserver.

ThesameWebapplicationcanbedeployedinmorethanoneenterprise

application,andonmorethanoneapplicationserver.

TheeasiestwaytodeployaWebapplicationusingWSADistosimply

runitonaserver;itwillbeautomaticallydeployed,ifnecessary.Todoso,

selecttheSampleServletproject,right-click,andselectRunonServer….

Thefirsttimeyouruntheproject,theserverselectiondialogisdisplayed.

ClicktheAdvancedbuttonandtheserverselectionwizardshownin

Figure8.4isdisplayedtocreateaservertouse.



Figure8.4.Serverselectionwizard.



SelecttheCreateanewserverradiobutton,thentheWTEserver.This



serverisbuiltintoWSADandsimplifiesdevelopmentbyrunningtheWeb

applicationinsideWSADanddirectlyfromthefileslocatedinthe

Workbench'sprojects.CheckthetoggleSetthisserverasprojectdefault

(donotprompt)tosetthisserverasthepreferredonefortheSample

Servletproject(youcancreateasmanyserversasyouwant)andselect

thepreferredserverintheserverpreferencepropertiesoftheWeb

project.ToseetheWebprojectproperties,selecttheproject,right-click,

andselectproperties.ThepropertiesyousetwhenyoucreatedtheWeb

projectareavailableinthepropertiesdialogandcanbeupdatedas

needed.Inparticular,seetheServerPreference,andWebproperties

pages.

ClickNextontheServerselectionwizardandansweryestotheprompt

forcreatingaserverproject.Serverprojectscontainserverconfigurations

thatyoucanusetodeployandtestyourJ2EEapplications.Onthenext

page,youcansetanHTTPportnumberfortheserver.Ifyouhave

createdmanyservers,makesureeachoneislisteningonadifferent

HTTPportifyouintendtorunthematthesametime.Otherwise,the

serverwon'tbeabletostartupifitsportisalreadyinuse.ClickFinishto

createandstartuptheserver.You'llseeaWebbrowseropenupin

WSADasshowninFigure7.4.ClicktheBrowseEmployeeslinkandsee

whathappens.

Don'tbealarmedaboutallthoseerrorsthatappearedintheconsole

windowfromtheWebserver!OneofthechallengesofWebapplication

developmentisthaterrorsthatoccurincomponentsofyourapplication

areoftenreportedthroughtheapplicationserverratherthandirectlyby

yourapplication,ortheyappearaserrorsreturnedtotheclientWeb

browser,longaftertheerroroccurred.However,it'sgenerallyeasierto

findtheerrorthanitmayappear.Usuallythefirsterroristheoneyou

wanttoresolve.Theothersarejustcascadingerrorscausedbythefirst

one.Solet'slookattheconsoleoutputandseewhatcausedtheproblem



[10/28/029:57:06:123EST]726cdc0bHelpersWNMSV0605E:



upfromthecontext"java:"withthename"comp/env/jdbc/EJPB



NamingManagerandanexceptionresulted.Referencedatafoll



ReferenceFactoryClassName:com.ibm.ws.util.ResRefJndiLookupO

ReferenceFactoryClassLocationURLs:

ReferenceClassName:java.lang.Object

Type:ResRefJndiLookupInfo



Content:com.ibm.ws.util.ResRefJndiLookupInfo@9851c11ResRefJnd



Name="jdbc/EJPBOOK";JndiLookupInfo:jndiName="jdbc/EJPBOOK";

initialContextFactory=""



Exceptiondatafollows:

javax.naming.NameNotFoundException:jdbc/EJPBOOK



atcom.ibm.ws.naming.jndicos.CNContextImpl.doLookup(CNCo



atcom.ibm.ws.naming.jndicos.CNContextImpl.doLookup(CNCo





Fromtheconsoleoutputwecanseethata

javax.naming.NameNotFoundExceptionwasraisedwhenthe

EmployeegetDataSourcemethodattemptedtolookupthedatasource

namedjava:comp/env/jdbc/EJPBOOK.That'sbecausewehaven't

yetcreatedadatasourcefortheserverconfigurationtotellitwherethe



datasourceisandhowtoaccessit.

RecallthatwecreatedareferenceintheWebdeploymentdescriptortoa

javax.sql.DataSourceresourcecalledjdbc/EJPBOOKthatalso

usedjdbc/EJPBOOKastheJNDIname.However,wenevercreatedthe

resourceintheJNDIserver.Thenexttwosectionscovertheremaining

configurationoperations.



8.1.2ConfiguretheEnterpriseApplicationto

DeploytheWebApplication

NowthattheWebapplicationhasbeendeployed,let'slookatwhathas

happened.First,referringtoFigure7.8,recallthatwhenyoucreatedthe

ServletExampleWebapplication,youhadtospecifyanenterprise

applicationtodeploytheWebapplicationtoaJ2EEWebapplication.

Second,whenyourantheWebapplicationonaserver,theservlet

selectionwizard(Figure8.4)wasdisplayedbecausetherewereno

definedservers,and,therefore,theWebapplicationhasnopreference.

SelectingtheWebapplicationandinvokingRunonServerusesthe

enterpriseapplicationspecifiedwhentheWebapplicationwascreated

andinvokestheserverselectionwizardtocreateaserverinstance,or

reuseone,andpublishtheenterpriseapplicationtothatserver.Eachof

theseactivitiescanbedonemanually,enablingmoreconfiguration

control.

Toedittheenterpriseapplication,expandtheprojectcorrespondingto

theenterpriseapplicationyouenteredwhencreatingtheWebapplication

asshowninFigure7.8.Ifyoutookthedefault,theenterpriseapplication

wouldbeDefaultEAR.Double-clicktheEARDeploymentDescriptorin

theDefaultEARproject(rightundertheprojectname),oreditthe

application.xmlfileintheMETA-INFfolder.Thisinvokesthe

ApplicationDeploymentDescriptoreditorshowninFigure8.5.



Figure8.5.Applicationdeploymentdescriptor,module



page.



TheOverviewtabprovidesanoverviewoftheenterpriseapplication

givingitsname,description,alistofWebandEJBarchivemodulesthat

areincludedintheapplication,andotherdetailsasspecifiedintheJ2EE

1.3specification.

UsetheModulestabtoaddorremoveWeborEJBmodulesto/fromthe

enterpriseapplication.Anenterpriseapplicationcanhostanynumberof

WARfiles,JARfiles,andotherprojectutilityJARsthatcontainJava

classesusedbyothermodulesintheenterpriseapplication.Noticethat

thecreateWebapplicationwizardshowninFigure7.8addedthesample

servletapplicationtotheDefaultEARfilesinceweselectedthatoption.

Youcanalsoaddandremovemodulesfromtheenterpriseapplication

usingthebuttonsatthebottomofthemodulelist.

EachmodulehasaURItotheWARorJARfilethatprovidethemodule

implementation,andthecontextrootthatspecifiestheURLprefixusedto

accessresourcesinthatmodule.Thecontextrootmustmatchthevalue

givenintheWebpropertiesoftheWebapplicationproject.TheSecurity

taballowsyoutodefinesecurityrolesfortheenterpriseapplication,and

assignparticularusersorgroupstothoseroles.



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

Chapter 8. Testing Servlets Using WSAD

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

×