Tải bản đầy đủ (.pdf) (634 trang)

Apress pro jakarta tomcat 5 dec 2004 ISBN 1590593316

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.65 MB, 634 trang )


ProJakartaTomcat5
MATTHEWMOODIE
Apress

©2005byMatthewMoodie
Allrightsreserved.Nopartofthisworkmaybereproducedor
transmittedinanyformorbyanymeans,electronicormechanical,
includingphotocopying,recording,orbyanyinformationstorageor
retrievalsystem,withoutthepriorwrittenpermissionofthecopyright
ownerandthepublisher.
ISBN(pbk):1590593316
Trademarkednamesmayappearinthisbook.Ratherthanusea
trademarksymbolwitheveryoccurrenceofatrademarkedname,we


usethenamesonlyinaneditorialfashionandtothebenefitofthe
trademarkowner,withnointentionofinfringementofthetrademark.
LeadEditor:SteveAnglin
TechnicalReviewer:ScottDavis
EditorialBoard:SteveAnglin,DanAppleman,Ewan
Buckingham,GaryCornell,TonyDavis,JohnFranklin,Jason
Gilmore,ChrisMills,DominicShakeshaft,JimSumser
ProjectManager:TracyBrownCollins
CopyEditManager:NicoleLeClerc
CopyEditor:KimWimpsett
ProductionManager:KariBrooks-Copony
ProductionEditor:KatieStence
Compositor:SusanGlinert
Proofreader:LizWelch
Indexer:KevinBroccoli


Artist:AprilMilne
CoverDesigner:KurtKrames
ManufacturingManager:TomDebolski
DistributedtothebooktradeintheUnitedStatesbySpringer-Verlag
NewYork,Inc.,233SpringStreet,6thFloor,NewYork,NY10013,
andoutsidetheUnitedStatesbySpringer-VerlagGmbH&Co.KG,
Tiergartenstr.17,69112Heidelberg,Germany.
IntheUnitedStates:phone1-800-SPRINGER,fax201-348-4505,email,orvisit.
OutsidetheUnitedStates:fax+496221345229,e-mail


,orvisit.
Forinformationontranslations,pleasecontactApressdirectlyat2560
NinthStreet,Suite219,Berkeley,CA94710.Phone510-549-5930,
fax510-549-5939,e-mail,orvisit
.
Theinformationinthisbookisdistributedonan“asis”basis,without
warranty.Althougheveryprecautionhasbeentakeninthe
preparationofthiswork,neithertheauthor(s)norApressshallhave
anyliabilitytoanypersonorentitywithrespecttoanylossordamage
causedorallegedtobecauseddirectlyorindirectlybytheinformation
containedinthiswork.
Thesourcecodeforthisbookisavailabletoreadersat
intheDownloadssection.
Dedication
ToLaura
AbouttheAuthor
MATTHEWMOODIEisanativeofsouthwestScotlandandisa
graduateoftheUniversityofEdinburgh,whereheobtainedamaster’s
degreeinlinguisticsandartificialintelligence.

MatthewenjoysalifeoffuninGlasgow,Scotland.He’sakeennovice
gardenerwithahousefulofplants.
AbouttheTechnicalReviewer
SCOTTDAVISisaseniorsoftwareengineerandinstructorinthe
Denver,Colorado,area.HehasworkedonavarietyofJava
platforms,includingJ2EE,J2SE,andJ2ME(sometimesallonthe
sameproject).He’safrequentpresenteratnationalconferencesand
localusergroups.HewasthepresidentoftheDenverJavaUsers
Group()in2003whenitwasvotedoneof
thetop-tenJUGsinNorthAmerica.Keepupwithhimat
.


Acknowledgments
MatthewwouldliketothankLauraforherloveandfriendship.
Lovetohismum,Valla,Alexandra,Harcus,Angus,Howardandhis
grandparents.ThanksgotoAndrew,Brian,Katy,LindseyandDisco
RobotCraigforthegoodtimes.BigshoutouttotheLochmabenboys
BillyandDave.Seeyoudownthegaff.Andnotforgettingthe
LockerbiewhistleposseofPete,Broon,StuartandMark
(Carrutherstowndoesn’tcount).


ProJakartaTomcat5
byMatthewMoodie
Apress2005(400pages)
ISBN:1590593316

IdealforTomcatadministratorsandthosewhowishto
configureTomcat,thissuccincttextdescribes

configurationfiles,aswellasadministrationfeatures
likesecurity,auto-deployment,remotedeployment,
anddatasources.

TableofContents
ProJakartaTomcat5
Chapter1 - IntroducingTomcat
Chapter2 - InstallingTomcat
Chapter3 - ExaminingTomcat’sDirectories
Chapter4 - WorkingwithTomcat’sConfigurationFiles
Chapter5 - AdministeringWebApplications
Chapter6 - UsingTomcat’sAdministrationTools
Chapter7 - ConfiguringTomcat
Chapter8 - UnderstandingTomcat’sClassLoaders
Chapter9 - UsingTomcat’sConnectors
Chapter10 - ConnectingtoDatabasesUsingJDBC
Chapter11 - WorkingwithUserAuthentication
Chapter12 - SecuringTomcat
Chapter13 - ImplementingSharedTomcatHosting
Chapter14 - TestingTomcat’sPerformance
AppendixA - Tomcat’sLog4JLoggers
AppendixB - InstallingMySQL



Chapter1:IntroducingTomcat
This,asbefitsafirstchapterinabookonTomcat,isashorthistoryof
dynamicWebcontentandhowTomcatfitsintothathistory.Once
you’vedealtwiththat,you’lllearnaboutTomcat’sarchitectureandits
modularapproachtoconfiguration.



UnderstandingtheWebToday
TheWebisn’tsolelymadeupofstaticpagesthatshowthesame
documenttoeveryuser;manypagescontaincontentgenerated
independentlyforeachviewer.Althoughstaticfilesstillhavetheir
place,manyusefulandnecessaryWebsiteswouldbeunableto
functionwithoutdynamiccontent.Forexample,Amazon.comisoneof
themajorsuccessstoriesoftheWebandisoftenthereasonpeople
goonlineforthefirsttime.Withoutdynamiccontent,suchasshopping
baskets,personalrecommendations,andpersonalizedwelcome
messages,Amazon.comwouldn’tbethesuccessithasbeen,and
manypeoplewouldn’tbeonline.
TheCommonGatewayInterface(CGI)wastheoriginaldynamic
contentmechanismthatexecutedprogramsonaWebserverand
allowedWebmasterstocustomizetheirpages,whichwasextremely
popularintheearlydaysoftheWeb.TheCGImodelisasfollows:
1. Thebrowsersendsarequesttotheserverjustasitwould
foraHypertextMarkupLanguage(HTML)page.
2. Theservermapstherequestedresourcetoanexternal
program.
3. Theserverrunstheexternalprogramandpassesitthe
originalHypertextTransferProtocol(HTTP)request.
4. Theexternalprogramexecutesandsendsitsresultstothe
server.
5. Theserverpassestheprogram’soutputtothebrowseras
anHTTPresponse.
CGIhasbeenimplementedinmanyprogramminglanguages,butPerl
was,andstillis,themostpopularlanguagefordevelopingCGI
applications.However,CGIisn’tveryefficient;eachtimetheserver

receivesarequest,itmuststartanewcopyoftheexternalprogram.


So,ifonlyasmallnumberofusersrequestaCGIprogram
simultaneously,it’snottoobigofaproblem.However,it’sadifferent
storyifhundredsorthousandsofusersrequesttheresource
simultaneously.Everycopyoftheprogramrequiresashareofthe
server’sprocessingpower,whichisrapidlyusedupasrequestspile
up.ThesituationismadeevenworsewithCGIprogramsthatare
writtenininterpretedlanguagessuchasPerl,whichresultinthe
launchoflargeruntimeinterpreterswitheachrequest.

LookingBeyondCGI
ManyalternativesolutionstoCGIhavebeendevelopedsincethe
Webbegan.Themoresuccessfuloftheseprovideanenvironment
thatexistsinsideanexistingserverorevenfunctionsasaserveron
itsown.
ManyCGIreplacementshavebeenbuiltontopoftheApacheserver
()becauseofApache’spopularmodular
applicationprogramminginterface(API).DeveloperscanusetheAPI
toextendApache’sfunctionalitywithpersistentprograms,andthusit’s
idealforcreatingprogramsthatcreatedynamiccontent.Apacheloads
modulesintoitsmemorywhenitstartsandpassestheappropriate
HTTPrequeststothemasappropriate.ItthenpassestheHTTP
responsestothebrowseroncethemoduleshaveprocessedthe
requests.Becausethemodulesarealreadyintheserver’smemory,
thecostofloadinganinterpreterisremovedandscriptscanexecute
faster.
Althoughfewdevelopersactuallycreatemodulesthemselves(they’re
relativelydifficulttodevelop),manythird-partymodulesprovidea

basisforapplicationsthataremuchmoreefficientthannormalCGI.
Thefollowingareafewexamples:
mod_perl:ThismaintainsthePerlinterpreterinmemory,
thusremovingtheoverheadofloadinganewcopyofthePerl
interpreterforeachrequest.Thisisanincrediblypopular
module.


mod_php4:ThismodulespeedsupPHPinthesameway
thatmod_perlspeedsupPerl.
mod_fastcgi:ThisissimilartostraightCGI,butitkeeps
programsinmemoryratherthanterminatingthemwheneach
requestisfinished.
MicrosoftprovidesaninterfacetoitsInternetInformationServices
(IIS)Webserver,calledtheInternetServerApplicationProgramming
Interface(ISAPI).ThisAPIdoesn’thavethefollowingthatApache’s
APIhasbecauseofitscomplexity,butit’sneverthelessahighperformanceAPI.However,IISiswidelyused,mainlybecauseit
comesaspartofmanyversionsofWindows.InChapter9you’ll
configureTomcattoworkwithIISsoyoucancombinethebest
featuresofboth.
MicrosoftalsodevelopedtheActiveServerPages(ASP)technology,
whichletsyouembedscripts,typicallyVBScript,intostandardHTML
pages.Thismodelhasprovedextremelysuccessfulandwasthe
catalystforJavaWebtechnology,whichI’lldiscussnext.

IntroducingJavaontheWeb
Javawasinitiallyreleasedinthemid-1990sasawaytolivenupstatic
Webpages.Itwasplatformindependentandalloweddevelopersto
executetheirprograms,calledapplets,intheuser’sbrowser.An
incredibleamountofhypesurroundedapplets:thattheywouldmake

theWebmoreexcitingandinteractive,thattheywouldchangethe
waypeopleboughtcomputers,andthattheywouldreduceallthe
variousoperatingsystemsintomereplatformsforWebbrowsers.
Appletsneverreallycaughton;infact,othertechnologies,suchas
MacromediaFlash,becamemorepopularwaysofcreatinginteractive
Websites.However,Javaisn’tjustforwritingapplets:youcanalso
useittocreatestand-aloneplatform-independentapplications.
ThemaincontributionofJavatotheWebisservlets,whichare
anotheralternativetechnologytoCGI.JustasCGIanditsother


alternativesaren’tstand-aloneprograms(becausetheyrequireaWeb
server),servletsrequireaservletcontainertoloadservletsinto
memory.TheservletcontainerthenreceivesHTTPrequestsfrom
browsersandpassesthemtoservletsthatgeneratetheresponse.
TheservletcontainercanalsointegratewithotherWebserverstouse
theirmoreefficientstaticfileabilitieswhilecontinuingtoproducethe
dynamiccontent.You’llfindanexampleofthisinChapter9whenyou
integrateTomcatwithApacheandIIS.
Unfortunately,althoughservletsareanimprovementoverCGI,
especiallywithrespecttoperformanceandserverload,theytoohave
adrawback.They’reprimarilysuitableforprocessinglogic.Forthe
creationofcontent(thatis,HTML),they’relessusable.First,hardcodingtextualoutput,includingHTMLtags,incodemakesthe
applicationlessmaintainable.ThisisbecauseiftextintheHTMLmust
bechanged,theservletmustberecompiled.
Second,thisapproachrequirestheHTMLdesignertounderstand
enoughaboutJavatoavoidbreakingtheservlet.Morelikely,
however,theprogrammeroftheapplicationmusttaketheHTMLfrom
thedesignerandthenembeditintotheapplication:anerror-prone
taskifevertherewasone.

Tosolvethisproblem,SunMicrosystemscreatedtheJavaServer
Pages(JSP)technology.

AddingtoServlets:JavaServerPages
AlthoughwritingservletsrequiresknowledgeofJava,aJavanewbie
canquicklylearnsomeusefulJSPtechniques.Assuch,JSP
representsaviableandattractivealternativetoMicrosoft’sASP.
Practicallyspeaking,JSPpagesarecompiledintoservlets,whichare
thenkeptinmemoryoronthefilesystemindefinitely,untileitherthe
memoryisrequiredortheserverisrestarted.Thisservletiscalledfor
eachrequest,thusmakingtheprocessfarmoreefficientthanASP,
sinceASPrequirestheservertoparseandcompilethedocument
everytimeausercomestothesite.Thismeansthatadevelopercan


writesoftwarewhoseoutputiseasytoverifyvisuallyandthatthe
resultworkslikeapieceofsoftware.Infact,JSPtookoffmainlyasa
resultofitssuitabilityforcreatingdynamicvisualcontentatatime
whentheInternetwasgrowinginpopularity.
OnemajorpracticaldifferencebetweenservletsandJSPpagesisthat
servletsareprovidedincompiledformandJSPpagesareoftennot
(althoughprecompilationispossible).Whatthismeansforasystem
administratoristhatservletfilesareheldintheprivateresources
sectionoftheservletcontainer,andJSPfilesaremixedinwithstatic
HTMLpages,images,andotherresourcesinthepublicsectionof
servletcontainer.



IntroducingServletContainers

JSPpagesandservletsrequireaservletcontainertooperateatall.
Tomcat,thesubjectofthisbook,isthereferenceimplementation(RI)
servletcontainer,whichmeansthatTomcat’sfirstpriorityistobefully
compliantwiththeServletandJSPspecificationspublishedbySun
Microsystems.However,thisisn’ttosaythatTomcatisn’tworthyof
useinproductionsystems.Indeed,manycommercialinstallationsuse
Tomcat.
AnRIhastheaddedbenefitofrefiningthespecification,whateverthe
technologymaybe.Asdevelopersaddcodeperthespecifications,
theycanuncoverproblemsinimplementationrequirementsand
conflictswithinthespecification.
Asnotedpreviously,theRIiscompletelycompliantwiththe
specificationandisthereforeparticularlyusefulforpeoplewhoare
usingadvancedfeaturesofthespecification.TheRIisreleasedwith
thespecification,whichmeansthatTomcatisalwaysthefirstserverto
providethenewfeaturesofthespecificationwhenit’sfinished.

LookingatTomcat
Tomcathasitsoriginsintheearliestdaysoftheservlettechnology.
SunMicrosystemscreatedthefirstservletcontainer,theJavaWeb
Server,todemonstratethetechnology,butitwasn’tterriblyrobust.At
thesametime,theApacheSoftwareFoundation(ASF)createdJServ,
aservletenginethatintegratedwiththeApacheWebserver.
In1999,SunMicrosystemsdonatedtheJavaWebServercodetothe
ASF,andthetwoprojectsmergedtocreateTomcat.Version3.xwas
thefirstTomcatseriesandwasdirectlydescendedfromtheoriginal
codethatSunMicrosystemsprovidedtotheASF.It’sstillavailable
andistheRIoftheServlet2.2andJSP1.1specifications.
In2001,theASFreleasedTomcat4.0,whichwasacomplete
redesignoftheTomcatarchitectureandwhichhadanewcodebase.

TheTomcat4.xseriesistheRIoftheServlet2.3andJSP1.2


specifications.
Tomcat5.xisthecurrentTomcatversionandistheRIoftheServlet
2.4andJSP2.0specifications.Assuch,thisistheversionofTomcat
you’lluseinthisbook.NotethattwobranchesofTomcat5.xexist:
Tomcat5.0.xandTomcat5.5.x.Tomcat5.5.xbranchedatTomcat
5.0.27andisarefactoredversionthat’sintendedtoworkwiththe
proposedJava2PlatformStandardEdition5.0(thoughyoucanuseit
withJava2StandardEdition1.4).Youshouldgetnodiscrepancy
betweentheserverswhentheyrunWebapplications.Themain
differencesareinconfiguration.Whereaconfigurationdiscrepancy
exists,I’llgivetherelevantdetails.



UnderstandingTomcat’sArchitecture
ThelatestversionofTomcatis5.x,whichsupportstheServlet2.4and
JSP2.0specifications.Itconsistsofanestedhierarchyof
components.
Top-levelcomponentsexistatthetopoftheconfiguration
hierarchyinarigidrelationshipwithoneanother.
Connectorsconnecttheservletcontainertorequests,either
fromabrowseroranotherWebserverthat’shandlingthe
staticresources.
Containercomponentscontainacollectionofother
components.
Nestedcomponentscanresideincontainersbutcan’tcontain
othercomponents.

Figure1-1illustratesthestructureofaTomcatconfiguration.

Figure1-1:Anexample
Tomcatconfiguration.Thecomponentsmarkedwithastarcan
occurmultipletimes.
WhenconfiguringTomcat,youcanremovesomeoftheseobjects
withoutaffectingtheserver.Notably,theengineandhostmaybe
unnecessaryifyou’reusingaWebserversuchasApache.
Youwon’tbesurprisedtohearthatTomcatisconfiguredwithan


ExtensibleMarkupLanguage(XML)filethatmirrorsthecomponent
hierarchy.You’lllearnaboutthisfile,calledserver.xml,inChapter
4.
Inthenextcoupleofsections,you’lllookintoeachcomponentinturn.

Top-LevelComponents
Thetop-levelcomponentsaretheTomcatserver,asopposedtothe
othercomponents,whichareonlypartsoftheserver.

TheServerComponent
TheservercomponentisaninstanceoftheTomcatserver.Youcan
createonlyoneinstanceofaserverinsideagivenJavavirtual
machine(JVM).
Youcansetupseparateserversconfiguredtodifferentportsona
singleservertoseparateapplicationssothatyoucanrestartthem
independently.So,ifagivenJVMcrashes,theotherapplicationswill
besafeinanotherinstanceoftheserver.Thisissometimesdonein
hostingenvironmentswhereeachcustomerhasaseparateinstance
ofaJVMsothatabadlywrittenapplicationwon’tcauseothersto

crash.

TheServiceComponent
Aservicecomponentgroupsanenginecomponentwithits
connectors.Anengineisarequest-processingcomponentthat
representstheservletengine.ItexaminestheHTTPheadersto
determinetowhichhostorcontext(thatis,whichWebapplication)it
shouldpasstherequest.Eachserviceisnamedsothatadministrators
caneasilyidentifylogmessagessentfromeachservice.
So,thiscomponentacceptsrequests,routesthemtotheappropriate
Webapplication,andreturnstheresultoftherequestprocessing.

TheConnectorComponents


ConnectorsconnectWebapplicationstoclients.They’rethepoint
whererequestsarereceivedfromclients,andeachhasauniqueport
ontheserver.Tomcat’sdefaultHTTPportis8080toavoid
interferencewithanyWebserverrunningonport80,thestandard
HTTPport.However,youcanchangethisaslongasthenewport
doesn’talreadyhaveaserviceassociatedwithit.
ThedefaultHTTPconnectorimplementsHTTP1.1.Thealternativeis
theApacheJServProtocol(AJP)connector,whichisaconnectorfor
linkingwithApacheinordertouseitsSecureSocketsLayer(SSL)
andstaticcontent-processingcapabilities.I’lldiscusseachofthesein
Chapter9.

TheContainerComponents
Thecontainercomponentsreceivetherequestsfromthetop-level
componentsasappropriate.Theythendealwiththerequestprocess

andreturntheresponsetothecomponentthatsentittothem.

TheEngineComponent
Theenginecomponentisthetop-levelcontainerandcan’tbe
containedbyanothercontainercomponent.Onlyonemaybe
containedineachservicecomponent.
Thetop-levelcontainerdoesn’thavetobeanengine,becauseitonly
hastoimplementthecontainerinterface.Thisinterfaceensuresthe
objectimplementingitisawareofitspositioninthecomponent
hierarchy,providesarealmforuserauthenticationandrole-based
authorization,andhasaccesstoanumberofresourcesincludingits
sessionmanagerandsomeimportantinternalstructures.
Thecontaineratthislevelisusuallyanengine,soyou’llseeitinthat
role.Asmentionedearlier,thecontainercomponentsarerequestprocessingcomponents,andtheengineisnoexception.Inthiscaseit
representstheCatalinaservletengine.ItexaminestheHTTPheaders
todeterminetowhichvirtualhostorcontexttopasstherequest.In
thiswayyoucanseetheprogressionoftherequestfromthetop-level


componentsdownthehierarchyofcomponents.
IfTomcatisusedasastand-aloneserver,thedefinedengineisthe
default.However,ifTomcatisconfiguredtoprovideservletsupport
withaWebserverprovidingthestaticpages,thedefaultengineis
overridden,astheWebserverhasnormallydeterminedthecorrect
destinationfortherequest.
Thehostnameoftheserverissetintheenginecomponentif
required.AnenginemaycontainhostsrepresentingagroupofWeb
applicationsandcontexts,eachrepresentingasingleWeb
application.


TheHostComponent
AhostcomponentisanalogoustotheApachevirtualhost
functionality.Thisallowsmultipleserverstobeconfiguredonthe
samephysicalmachineandbeidentifiedbyseparateInternet
Protocol(IP)addressesorhostnames.InTomcat’scase,thevirtual
hostsaredifferentiatedbyafullyqualifiedhostname.Thus,youcan
haveandonthesame
server.Inthiscase,theservletcontainerroutesrequeststothe
differentgroupsofWebapplications.
Whenyouconfigureahost,yousetitsname;themajorityofclients
willusuallysendboththeIPaddressoftheserverandthehostname
theyusedtoresolvetheIPaddress.Theenginecomponentinspects
theHTTPheadertodeterminewhichhostisbeingrequested.

TheContextComponent
Thefinalcontainercomponent,andtheoneatthelowestlevel,isthe
context,alsoknownastheWebapplication.Whenyouconfigurea
context,youinformtheservletcontainerofthelocationofthe
application’srootfoldersothatcomponentsthatcontainthis
componentcanrouterequestseffectively.Youcanalsoenable
dynamicreloadingsothatanyclassesthathavechangedare
reloadedintomemory.Thismeansthelatestchangesarereflectedin


theapplication.However,thisisresourceintensiveandisn’t
recommendedfordeploymentscenarios.
Acontextcomponentmayalsoincludeerrorpages,whichwillallow
youtoconfigureerrormessagesconsistentwiththeapplication’slook
andfeel.
Finally,youcanalsoconfigureacontextwithinitializationparameters

fortheapplicationitrepresentsandforaccesscontrol(authentication
andauthorizationrestrictions).Moreinformationonthesetwoaspects
ofWebapplicationdeploymentisavailableinChapter5.

TheNestedComponents
Thenestedcomponentsarenestedwithincontainercomponentsand
provideanumberofadministrativeservices.Youcan’tnestallofthem
ineverycontainercomponent,butyoucannestmanyofthemthis
way.Theexceptiontothecontainercomponentruleistheglobal
resourcescomponent,whichyoucannestonlywithinaserver
component.

TheGlobalResourcesComponent
Asalreadymentioned,thiscomponentmaybenestedonlywithina
servercomponent.YouusethiscomponenttoconfigureglobalJava
NamingandDirectoryInterface(JNDI)resourcesthatalltheother
componentsintheservercanuse.Typicallythesecouldbedata
sourcesfordatabaseaccessorserverwideconstantsforusein
applicationcode.

TheLoaderComponent
Theloadercomponentmaybenestedonlywithinacontext
component.YouusealoadertospecifyaWebapplication’sclass
loader,whichwillloadtheapplication’sclassesandresourcesinto
memory.TheclassloaderyouspecifymustfollowtheServlet
specification,thoughit’sunlikelyyou’llfinditnecessarytousethis
component,becausethedefaultclassloaderworksperfectlywell.


TheLoggerComponent

ThiscomponentisavailableonlyinTomcat5.0.xandnotinTomcat
5.5.x.YoushouldusealoggingimplementationsuchasLog4Jwith
Tomcat5.5.x,moreofwhichiscoveredinChapter4.
Aloggercomponentreportsontheinternalstateofitsparent
component.Youcanincludealoggerinanyofthecontainer
components.Loggingbehaviorisinherited,soaloggersetatthe
enginelevelisassignedtoeverychildobjectunlessoverriddenbythe
child.Theconfigurationofloggersatthislevelcanbeaconvenient
waytodecidethedefaultloggingbehaviorfortheserver.
Thisallowsyoutoconfigureaconvenientdestinationforalllogging
eventsforthecomponentsthataren’tconfiguredtogeneratetheir
ownlogs.

TheManagerComponent
Themanagercomponentrepresentsasessionmanagerforworking
withusersessionsinaWebapplication.Assuch,itcanbeincluded
onlyinacontextcontainer.Adefaultmanagercomponentisusedif
youdon’tspecifyanalternative,and,liketheloadercomponent
mentionedpreviously,you’llfindthatthedefaultisperfectlygood.

TheRealmComponent
Therealmforanenginemanagesuserauthenticationand
authorization.Aspartoftheconfigurationofanapplication,youset
therolesthatareallowedtoaccesseachresourceorgroupof
resources,andtherealmisusedtoenforcethispolicy.
Realmscanauthenticateagainsttextfiles,databasetables,
LightweightDirectoryAccessProtocol(LDAP)servers,andthe
Windowsnetworkidentityoftheuser.You’llseemoreofthisin
Chapter11.
Arealmappliesacrosstheentirecontainercomponentinwhichit’s

included,soapplicationswithinacontainershareauthentication


resources.Bydefault,ausermuststillauthenticateseparatelytoeach
Webapplicationontheserver.(Thisiscalledsinglesign-on.)You’ll
seehowyoucanchangethisinChapter7.

TheResourcesComponent
Youcanaddtheresourcescomponenttoacontextcomponent.It
representsthestaticresourcesinaWebapplicationandallowsthem
tobestoredinalternativeformats,suchascompressedfiles.The
defaultismorethansufficientformostneeds.

TheValveComponent
Youcanusevalvecomponentstointerceptarequestandprocessit
beforeitreachesitsdestination.Valvesareanalogoustofiltersas
definedintheServletspecificationandaren’tintheJSPorServlet
specifications.Youmayplacevalvecomponentsinanycontainer
component.
Valvesarecommonlyusedtologrequests,clientIPaddresses,and
serverusage.Thistechniqueisknownasrequestdumping,anda
requestdumpervalverecordstheHTTPheaderinformationandany
cookiessentwiththerequest.Responsedumpinglogstheresponse
headersandcookies(ifset)toafile.
Valvesaretypicallyreusablecomponents,soyoucanaddand
removethemfromtherequestpathaccordingtoyourneeds;Web
applicationscan’tdetecttheirpresence,sotheyshouldn’taffectthe
applicationinanyway.(However,performancemaysufferifavalveis
added.)Ifyourusershaveapplicationsthatneedtointerceptrequests
andresponsesforprocessing,theyshouldusefiltersasperthe

Servletspecification.
Youcanuseotherusefulfacilities,suchaslisteners,whenconfiguring
Tomcat.However,filtersaren’tdefinedascomponents.You’lldeal
withtheminChapter7.



×