DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
6LQFHWKH&RQWDLQHU
UHDGVWKHVHUYOHWLQLW
SDUDPHWHUVRQO\
RQFH
\RX
VWLOO
FDQ·WFKDQJH\RXUHPDLODGGUHVV
GXULQJWKHOLIHRIWKHVHUYOHW
6RWKLVLVDGXPE
VROXWLRQ
,W·VVWLOOZD\EHWWHUWKDQ
SXWWLQJLWLQP\VHUYOHWVRXUFH
FRGH$OO,KDYHWRGRLVFKDQJH
WKH[PODQGKLWWKH´UHGHSOR\µ
EXWWRQDQGWKHQHZDGGUHVVZLOO
EHLQWKH6HUYOHW&RQÀJ
4
3OUMWHERESTHAT
hREDEPLOYvBUTTONON4OMCAT
$
7ITH4OMCATTHEREISNTA
ONEBUTTONREALLYSIMPLEADMINTOOL
FORDEPLOYMENTANDREDEPLOYMENT
ALTHOUGHTHEREISANADMINTOOLTHAT
SHIPSWITH4OMCAT"UTTHINKABOUT
ITWHATSTHEWORSTYOUHAVETODOTO
CHANGETHESERVLETSINITPARAMETERS
9OUMAKEAQUICKCHANGETOTHEWEB
XMLFILESHUTDOWN4OMCATBIN
SHUTDOWNSHTHENRESTART4OMCAT
BINSTARTUPSH/NRESTART4OMCAT
LOOKSINITSWEBAPPSDIRECTORYAND
DEPLOYSEVERYTHINGITFINDSTHERE
4
3UREITSEASYTOTELL4OMCAT
TOSHUTDOWNANDSTARTUPBUT
WHATABOUTTHEWEBAPPSTHATARE
RUNNING4HEYALLHAVETOGODOWN
$
4ECHNICALLYYES4AKINGYOUR
WEBAPPSDOWNSOTHATYOUCAN
REDEPLOYONESERVLETISALITTLEHARSH
ESPECIALLYIFYOUHAVEALOTOFTRAFFIC
ONYOURWEBSITE"UTTHATSWHY
MOSTOFTHEPRODUCTIONQUALITY7EB
#ONTAINERSLETYOUDOAHOTREDEPLOY
WHICHMEANSTHATYOUDONTHAVETO
RESTARTYOURSERVERORTAKEANYOTHER
WEBAPPSDOWN)NFACT4OMCATDOES
INCLUDEAMANAGERTOOLTHATWILLLET
YOUDEPLOYUNDEPLOYANDREDEPLOY
ENTIREWEBAPPSWITHOUTRESTARTING
4OMCAT)NAPRODUCTIONENVIRONMENT
THATSWHATYOUDUSE"UTFORTESTING
ITSEASIERTOJUSTRESTART4OMCAT)NFO
ONTHEMANAGEMENTTOOLISAT
HTTPJAKARTAAPACHEORGTOMCAT
TOMCATDOCMANAGERHOWTOHTML
"UTINTHEREALWORLDEVENAHOT
REDEPLOYISA"IG$EALANDTAKING
EVENASINGLEAPPDOWNJUSTBECAUSE
THEINITPARAMETERVALUECHANGED
CANBEABADIDEA)FTHEVALUESOF
YOURINITPARAMETERSAREGOINGTO
CHANGEFREQUENTLYYOUREBETTEROFF
HAVINGYOURSERVLETMETHODSGETTHE
VALUESFROMAFILEORDATABASEBUT
THISAPPROACHWILLMEANALOTMORE
OVERHEADEACHTIMEYOURSERVLETCODE
RUNSINSTEADOFONLYONCEDURING
INITIALIZATION
WKHUH DUH QR
'
XPE 4XHVWLRQV
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
<M[\QVOaW]Z;MZ^TM\+WVNQO
3ERVLET#ONlGSMAINJOBISTOGIVEYOUINITPARAMETERS)TCAN
ALSOGIVEYOUA3ERVLET#ONTEXTBUTWELLUSUALLYGETACONTEXTINA
DIFFERENTWAYANDTHEGET3ERVLET.AMEMETHODISRARELYUSEFUL
SXEOLFYRLGGR*HW+WWS6HUYOHW5HTXHVWUHTXHVW+WWS6HUYOHW5HVSRQVHUHVSRQVH
WKURZV,2([FHSWLRQ6HUYOHW([FHSWLRQ^
UHVSRQVHVHW&RQWHQW7\SH³WH[WKWPO´
3ULQW:ULWHURXW UHVSRQVHJHW:ULWHU
RXWSULQWOQ³WHVWLQLWSDUDPHWHUVEU!´
(QXPHUDWLRQH JHW6HUYOHW&RQ¿JJHW,QLW3DUDPHWHU1DPHV
ZKLOHHKDV0RUH(OHPHQWV^
RXWSULQWOQ³EU!SDUDPQDPH ³HQH[W(OHPHQW³EU!´
`
RXWSULQWOQ³PDLQHPDLOLV³JHW6HUYOHW&RQ¿JJHW,QLW3DUDPHWHU³PDLQ(PDLO´
RXWSULQWOQ³EU!´
RXWSULQWOQ³DGPLQHPDLOLV³JHW6HUYOHW&RQ¿JJHW,QLW3DUDPHWHU³DGPLQ(PDLO´
`
`
,QWKH''ZHE[POÀOH
ZHEDSS[POQV ´KWWSMDYDVXQFRP[POQVMHH´
[POQV[VL ´KWWSZZZZRUJ;0/6FKHPDLQVWDQFH´
[VLVFKHPD/RFDWLRQ ´KWWSMDYDVXQFRP[POQVMHHZHEDSSBB[VG´
YHUVLRQ ´´!
VHUYOHW!
VHUYOHWQDPH!%HHU3DUDP7HVWVVHUYOHWQDPH!
VHUYOHWFODVV!FRPH[DPSOH7HVW,QLW3DUDPVVHUYOHWFODVV!
LQLWSDUDP!
SDUDPQDPH!DGPLQ(PDLOSDUDPQDPH!
SDUDPYDOXH!OLNHZHFDUH#ZLFNHGO\VPDUWFRPSDUDPYDOXH!
LQLWSDUDP!
LQLWSDUDP!
SDUDPQDPH!PDLQ(PDLOSDUDPQDPH!
SDUDPYDOXH!EORRSHU#ZLFNHGO\VPDUWFRPSDUDPYDOXH!
LQLWSDUDP!
VHUYOHW!
VHUYOHWPDSSLQJ!
VHUYOHWQDPH!%HHU3DUDP7HVWVVHUYOHWQDPH!
XUOSDWWHUQ!7HVWHUGRXUOSDWWHUQ!
VHUYOHWPDSSLQJ!
ZHEDSS!
JHW,QLW3DUDPHWHU6WULQJ
(QXPHUDWLRQJHW,QLW3DUDPHWHU1DPHV
JHW6HUYOHW&RQWH[W
JHW6HUYOHW1DPH
LQWHUIDFH!!
6HUYOHW&RQILJ
Most people never
use this method.
,QDVHUYOHWFODVV
MDYD[VHUYOHW6HUYOHW&RQILJ
XVLQJ6HUYOHW&RQ¿J
SDFNDJHFRPH[DPSOH
LPSRUWMDYD[VHUYOHW
LPSRUWMDYD[VHUYOHWKWWS
LPSRUWMDYDLR
SXEOLFFODVV7HVW,QLW3DUDPVH[WHQGV+WWS6HUYOHW^
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
8KRK,MXVWUHDOL]HG
WKDWLQP\UHDODSS,·PXVLQJ
-63WRUHQGHUWKHSDJH6R
FDQD-63´VHHµDVHUYOHW·V
LQLWSDUDPHWHUV"
0W_KIVI2;8OM\[MZ^TM\
QVQ\XIZIUM\MZ['
!3ERVLET#ONlGISFORSERVLETCONlGURATIONITDOESNTSAY
*30#ONlG3OIFYOUWANTOTHERPARTSOFYOURAPPLICATION
TOUSETHESAMEINFOYOUPUTINTHESERVLETSINIT
PARAMETERSINTHE$$YOUNEEDSOMETHINGMORE
?PI\IJW]\\PM_Ia_MLQLQ\_Q\P\PMJMMZ
IXX'?MXI[[ML\PMUWLMTQVNW\W\PM2;8
][QVOIZMY]M[\I\\ZQJ]\M
7ECOULDDOITTHISWAY4HEREQUESTOBJECTLETSYOUSET
ATTRIBUTESTHINKOFTHEMASANAMEVALUEPAIRWHERETHE
VALUECANBEANYOBJECTTHATANYOTHERSERVLETOR*30THAT
GETSTHEREQUESTCANUSE4HATMEANSANYSERVLETOR*30TO
WHICHTHEREQUESTISFORWARDEDUSINGA2EQUEST$ISPATCHER
7ELLLOOKAT2EQUEST$ISPATCHERINDETAILATTHEENDOF
THISCHAPTERBUTFORNOWALLWECAREABOUTISGETTINGTHE
DATAINTHISCASETHEEMAILADDRESSTOTHEPIECESOFTHE
WEBAPPTHATNEEDITRATHERTHANJUSTONESERVLET
LQVLGHWKHGR3RVWPHWKRG
6WULQJFRORU UHTXHVWJHW3DUDPHWHU³FRORU´
%HHU([SHUWEH QHZ%HHU([SHUW
/LVWUHVXOW EHJHW%UDQGVFRORU
UHTXHVWVHW$WWULEXWH³VW\OHV´UHVXOW
Remember? We got the clientÕs
color choice from the request.
Then we instantiated and
used the MODEL to get the
info we need for the VIEW.
Then we set an ÒattributeÓ
in the request, and the JSP
we forward the request to
was able to get it.
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
;M\\QVOIZMY]M[\
I\\ZQJ]\M
_WZS[J]\WVTaNWZ\PM2;8\W
_PQKPaW]NWZ_IZLML\PMZMY]M[\
7ITHTHEBEERAPPITMADESENSETOSTORETHEMODELINFO
FORTHECLIENTSREQUESTINTHEREQUESTOBJECTBECAUSETHENEXT
STEPWASTOFORWARDTHEREQUESTTOTHE*30RESPONSIBLEFOR
CREATINGTHEVIEW3INCETHAT*30NEEDEDTHEMODELDATA
ANDTHEDATAWASRELEVANTTOONLYTHATPARTICULARREQUEST
EVERYTHINGWASlNE
"UTTHATDOESNTHELPUSWITHTHEEMAILADDRESSBECAUSEWE
MIGHTNEEDTOUSEITFROMALLOVERTHEAPPLICATION4HERE
ISAWAYTOHAVEASERVLETREADTHEINITPARAMETERSANDTHEN
STORETHEMINAPLACEOTHERPARTSOFTHEAPPCOULDUSEBUT
THENWEDHAVETOKNOWWHICHSERVLETWOULDALWAYSRUNlRST
WHENTHEAPPISDEPLOYEDANDANYCHANGESTOTHEWEBAPP
COULDBREAKTHEWHOLETHING.OTHATWONTDOEITHER
%XW,UHDOO\ZDQW$//WKHSDUWV
RIP\ZHEDSSWRKDYHDFFHVVWRWKH
HPDLODGGUHVV:LWKLQLWSDUDPHWHUV
,KDYHWRFRQÀJXUHWKHPLQWKH''IRU
HYHU\
VHUYOHWDQGWKHQKDYHDOOWKHVHUYOHWVPDNH
WKHPDYDLODEOHIRUWKH-63V+RZERULQJ
LVWKDW"1RWPDLQWDLQDEOHHLWKHU,
QHHGVRPHWKLQJPRUH
JOREDO
,ZRQGHULI
WKHUH·VVRPHWKLQJOLNH
LQLWSDUDPHWHUVIRUWKH
DSSOLFDWLRQ
"
LQLWSDUDPHWHUOLPLWDWLRQV
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
+WV\M`\QVQ\XIZIUM\MZ[\W\PMZM[K]M
#ONTEXTINITPARAMETERSWORKJUSTLIKESERVLETINITPARAMETERSEXCEPT
CONTEXTPARAMETERSAREAVAILABLETOTHEENTIREWEBAPPNOTJUST
ASINGLESERVLET3OTHATMEANSANYSERVLETAND*30INTHEAPP
AUTOMATICALLYHASACCESSTOTHECONTEXTINITPARAMETERSSOWEDONT
HAVETOWORRYABOUTCONlGURINGTHE$$FOREVERYSERVLETAND
WHENTHEVALUECHANGESYOUONLYHAVETOCHANGEITONEPLACE
,QWKH''ZHE[POÀOH
VHUYOHW!
VHUYOHWQDPH!%HHU3DUDP7HVWVVHUYOHWQDPH!
VHUYOHWFODVV!7HVW,QLW3DUDPVVHUYOHWFODVV!
VHUYOHW!
FRQWH[WSDUDP!
SDUDPQDPH!DGPLQ(PDLOSDUDPQDPH!
SDUDPYDOXH!FOLHQWKHDGHUURU#ZLFNHGO\VPDUWFRPSDUDPYDOXH!
FRQWH[WSDUDP!
You give it a param-name and param-value just like with
servlet init parameters, except this time itÕs in the
<context-param> element instead of <init-param>.
,QWKHVHUYOHWFRGH
RXWSULQWOQJHW6HUYOHW&RQWH[WJHW,QLW3DUDPHWHU³DGPLQ(PDLO´
Every servlet inherits a getServletContext() method
(and JSPs have special access to a context as well).
The getServletContext() method
returns, surprisingly, a ServletContext
object. And one of its methods is
getInitParameter().
6HUYOHW&RQWH[WFRQWH[W JHW6HUYOHW&RQWH[W
RXWSULQWOQFRQWH[WJHW,QLW3DUDPHWHU³DGPLQ(PDLO´
25
Here we broke out the code into TWO stepsÑ
getting the ServletContext reference, and calling
its getInitParameter() method.
We took the <init-param> element
out of the <servlet> element.
IMPORTANT!! The <context-param> is
for the WHOLE app, so its not nested
inside an individual <servlet> element!! Put
<context-param> inside the <web-app>
but OUTSIDE any <servlet> declaration.
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
:MUMUJMZ\PMLQNNMZMVKMJM\_MMV[MZ^TM\QVQ\
XIZIUM\MZ[IVLKWV\M`\QVQ\XIZIUM\MZ[
(ERESAREVIEWOFTHEKEYDIFFERENCESBETWEENCONTEXTINITPARAMETERSANDSERVLET
INITPARAMETERS0AYSPECIALATTENTIONTOTHEFACTTHATTHEYREBOTHREFERREDTOAS
INITPARAMETERSEVENTHOUGHONLYSERVLETINITPARAMETERSHAVETHEWORDhINITvIN
THE$$CONlGURATION
&RQWH[WLQLWSDUDPHWHUV 6HUYOHWLQLWSDUDPHWHUV
'HSOR\PHQW
'HVFULSWRU
ZHEDSS!
FRQWH[WSDUDP!
SDUDPQDPH!IRRSDUDPQDPH!
SDUDPYDOXH!EDUSDUDPYDOXH!
FRQWH[WSDUDP!
RWKHUVWXIILQFOXGLQJ
VHUYOHWGHFODUDWLRQV!
ZHEDSS!
:LWKLQWKHZHEDSS!HOHPHQWEXW127
ZLWKLQDVSHFLILFVHUYOHW!HOHPHQW
VHUYOHW!
VHUYOHWQDPH!
%HHU3DUDP7HVWV
VHUYOHWQDPH!
VHUYOHWFODVV!
7HVW,QLW3DUDPV
VHUYOHWFODVV!
LQLWSDUDP!
SDUDPQDPH!IRRSDUDPQDPH!
SDUDPYDOXH!EDUSDUDPYDOXH!
LQLWSDUDP!
RWKHUVWXII!
VHUYOHW!
:LWKLQWKHVHUYOHW!HOHPHQWIRUHDFK
VSHFLILFVHUYOHW
JHW6HUYOHW&RQWH[WJHW,QLW3DUDPHWHU³IRR´ JHW6HUYOHW&RQ¿JJHW,QLW3DUDPHWHU³IRR´
6HUYOHW&RGH
$YDLODELOLW\
7RDQ\VHUYOHWVDQG-63VWKDWDUHSDUW
RIWKLVZHEDSS
7RRQO\WKHVHUYOHWIRUZKLFKWKHLQLWSDUDP!ZDV
FRQILJXUHG
$OWKRXJKWKHVHUYOHWFDQFKRRVHWRPDNHLWPRUH
ZLGHO\DYDLODEOHE\VWRULQJLWLQDQDWWULEXWH
FRQWH[WYVVHUYOHWLQLWSDUDPHWHUV
Notice it doesnÕt say ÒinitÓ
anywhere in the DD for context
init parameters, the way it does
for servlet init parameters.
ItÕs the same method name!
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
:DWFKLW
<RXUHDOO\KDYHWRNHHSWKHVHVWUDLJKWRQ
WKHH[DPDQGLW¶VWULFN\<RX0867NQRZ
WKDWERWK6HUYOHW&RQ¿JDQG6HUYOHW&RQWH[W
KDYHLQLWSDUDPHWHUVDQGERWKKDYHWKH
VDPHJHWWHUPHWKRG²JHW,QLW3DUDPHWHU
%87\RXDOVRKDYHWRNQRZWKDWFRQWH[W
LQLWSDUDPHWHUVDUHVHWZLWKFRQWH[WSDUDP!
QRWLQVLGHDVHUYOHW!HOHPHQWZKLOHVHUYOHW
LQLWSDUDPHWHUVXVHLQLWSDUDP!LQVLGHWKH
LQGLYLGXDOVHUYOHW!GHFODUDWLRQVLQWKH''
'RQ·WFRQIXVH
6HUYOHW
&RQÀJ
SDUDPHWHUVZLWK
6HUYOHW
&RQWH[W
SDUDPHWHUV
; M Z ^ T M \
+WVNQO
Q[WVMXMZ[MZ^TM\
; M Z ^ T M \
+WV\M`\
Q[WVMXMZ_MJIXX
4HERESONLYONE3ERVLET#ONTEXTFORANENTIREWEBAPPANDALLTHE
PARTSOFTHEWEBAPPSHAREIT"UTEACHSERVLETINTHEAPPHASITSOWN
3ERVLET#ONlG4HE#ONTAINERMAKESA3ERVLET#ONTEXTWHENAWEB
APPISDEPLOYEDANDMAKESTHECONTEXTAVAILABLETOEACH3ERVLETAND
*30WHICHBECOMESASERVLETINTHEWEBAPP
&RQWDLQHUUHDGVWKH''DQG
FUHDWHVDQDPHYDOXH6WULQJSDLU
IRUHDFKFRQWH[WSDUDP!
&RQWDLQHUFUHDWHVDQHZLQVWDQFH
RI6HUYOHW&RQWH[W
&RQWDLQHUJLYHVWKH
6HUYOHW&RQWH[WDUHIHUHQFHWR
HDFKQDPHYDOXHSDLURIWKH
FRQWH[WLQLWSDUDPHWHUV
(YHU\VHUYOHWDQG-63GHSOR\HG
DVSDUWRIDVLQJOHZHEDSS
KDVDFFHVVWRWKDWVDPH
6HUYOHW&RQWH[W
:HEDSSLQLWLDOL]DWLRQ
app-wide context
init params inside
6HUYOHW$
6
H
U
Y
O
H
W
&
R
Q
I
L
J
6HUYOHW% 6HUYOHW&
6
H
U
Y
O
H
W
&
R
Q
I
L
J
6
H
U
Y
O
H
W
&
R
Q
I
L
J
6
H
U
Y
O
H
W
&
R
Q
W
H
[
W
KWPO!
ERG\!
MVSVHW3URSHUW\
QDPH ´IRR´
SURSHUW\ ´EDU´!
ERG\!
KWPO!
-63
init params for
Servlet C inside
init params for
Servlet B inside
init params for
Servlet A inside
:DWFKLW
,I\RXUDSSOLFDWLRQLVGLVWULEXWHGDFURVV
PXOWLSOHVHUYHUVSUREDEO\LQDFOXVWHUHG
HQYLURQPHQW\RXUZHEDSSUHDOO\&28/'
KDYHPRUHWKDQRQH6HUYOHW&RQWH[W$
6HUYOHW&RQWH[WLVRQHSHUDSSEXWRQO\LI
WKHDSSLVLQDVLQJOH-90
,QDGLVWULEXWHGHQYLURQPHQW\RX¶OOKDYHRQH
6HUYOHW&RQWH[WSHU-901RZFKDQFHVDUH
WKLVZRQ¶WFUHDWHSUREOHPVEXWLI\RXKDYHD
GLVWULEXWHGZHEDSS\RXEHWWHUFRQVLGHUWKH
FRQVHTXHQFHVRIKDYLQJGLIIHUHQWFRQWH[WV
IRUHDFK-90
,IWKHDSSLV
GLVWULEXWHGWKHUH·V
RQH6HUYOHW&RQWH[W
SHU-90
6
H
U
Y
O
H
W
&
R
Q
I
L
J
Yes, JSPs are turned into
Þ rst-class servlets, so
they also get their own
ServletConÞ g.
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
4
7HATSWITHTHEINCONSISTENTNAMINGSCHEME
(OWCOMETHE$$ELEMENTSARECONTEXTPARAMAND
INITPARAMBUTINTHESERVLETCODE"/4(USETHE
GET)NIT0ARAMETERMETHOD
$
4HEYDIDNTASKUSTOHELPTHEMCOMEUPWITHTHE
NAMES)FTHEYHADOFCOURSEWEDHAVESAIDITSHOULDBE
GET)NIT0ARAMETERANDGET#ONTEXT0ARAMETERTOMATCH
THE8-,ELEMENTSINTHE$$/RTHEYCOULDHAVEUSED
DIFFERENT8-,ELEMENTSPERHAPSSERVLETINITPARAM
ANDCONTEXTINITPARAM"UTNOTHATWOULDHAVESUCKED
ALLTHEFUNOUTOFTRYINGTOKEEPTHEMSTRAIGHT
4
7HYWOULD)EVERUSEINITPARAMANYWAY
7OULDNT)ALWAYSWANTTOUSECONTEXTPARAMSO
THATOTHERPARTSOFMYAPPCOULDREUSETHEVALUESAND
)WONTHAVETODUPLICATE8-,CODEFOREVERYSERVLET
DECLARATION
$
)TALLDEPENDSONWHICHPARTOFYOURAPPIS
SUPPOSEDTOSEETHEVALUE9OURAPPLICATIONLOGICMIGHT
REQUIREYOUTOUSEAVALUETHATYOUWANTTORESTRICTTO
ONLYANINDIVIDUALSERVLET"UTTYPICALLYDEVELOPERSFIND
APPWIDECONTEXTINITPARAMETERSALOTMOREHELPFULTHAN
SERVLETSPECIFICSERVLETINITPARAMETERS0ERHAPSTHEMOST
COMMONUSEOFACONTEXTPARAMETERISSTORINGDATABASE
LOOKUPNAMES9OUDWANTALLPARTSOFYOURAPPTOHAVE
ACCESSTOTHECORRECTNAMEANDWHENITCHANGESYOUWANT
TOCHANGEITINONLYONEPLACE
4
7HATHAPPENSIF)GIVEACONTEXTINITPARAMETER
THESAMENAMEASASERVLETINITPARAMETERINTHESAME
WEBAPP
$
4HEMOLECULARSIZEDBLACKHOLEMIRACULOUSLY
CREATEDINARESEARCHFACILITYIN.EW*ERSEYWILLSLIPFROMITS
CONTAINMENTlELDPLUMMETTOTHEEARTHSCOREANDDESTROY
THEPLANET
/RMAYBENOTHINGBECAUSETHERESNONAMESPACECONmICT
SINCEYOUGETTHEPARAMETERSTHROUGHTWODIFFERENTOBJECTS
3ERVLET#ONTEXTOR3ERVLET#ONlG
4
)FYOUMODIFYTHE8-,TOCHANGETHEVALUEOFAN
INITPARAMETEREITHERSERVLETORCONTEXTWHENDOESTHE
SERVLETORTHERESTOFTHEWEBAPPSEETHECHANGE
$
/.,9WHENTHEWEBAPPISREDEPLOYED
2EMEMBERWETALKEDABOUTTHISBEFORETHESERVLETIS
INITIALIZEDONLYONCEATTHEBEGINNINGOFITSLIFEANDTHATS
WHENITSGIVENITS3ERVLET#ONFIGAND3ERVLET#ONTEXT4HE
#ONTAINERREADSTHEVALUESFROMTHE$$WHENITCREATES
THOSETWOOBJECTSANDSETSTHEVALUES
4
#ANT)GETAROUNDTHISBYSETTINGTHEVALUESAT
RUNTIME3URELYTHERESAN!0)THATLLLETMECHANGE
THOSEVALUESDYNAMICALLY
$
.OTHERESNOT,OOKIN3ERVLET#ONTEXTOR
3ERVLET#ONFIGANDYOULLFINDAGETTERGET)NIT0ARAMETER
BUTYOUWONTFINDASETTER4HERESNOSET)NIT0ARAMETER
4
4HATSLAME
$
4HESEAREINITPARAMETERS)NITFROMTHE,ATINWORD
INITIALIZATION)FYOUTHINKOFTHEMPURELYASDEPLOYTIME
CONSTANTSYOULLHAVETHERIGHTPERSPECTIVE)NFACTTHATS
SOIMPORTANTWEREGOINGTOSAYITAGAININABOLDERWAY
7KLQNRILQLWSDUDPHWHUVDV
GHSOR\WLPHFRQVWDQWV
<RXFDQ
JHW
WKHPDWUXQWLPH
EXW\RXFDQ·W
VHW
WKHP7KHUH·V
QR
VHW
,QLW3DUDPHWHU
VHUYOHWDQGFRQWH[WLQLWSDUDPHWHUV
WKHUH DUH QR
'
XPE 4XHVWLRQV
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
6RPHSHRSOHXVHWKHSKUDVH³LQLWSDUDPHWHU´WRPHDQ³VHUYOHW
LQLWSDUDPHWHU´DQGWKH\XVH³FRQWH[WSDUDPHWHU´RUHYHQ³DS
SOLFDWLRQSDUDPHWHU´WRPHDQ³FRQWH[WLQLWSDUDPHWHU´6RHYHQ
WKRXJK%27+DUHLQLWLDOL]DWLRQSDUDPHWHUVDQGERWKFRPHIURP
WKHJHW,QLW3DUDPHWHUPHWKRGUHPHPEHUWKDWRQO\6(59/(7LQLW
SDUDPHWHUVDUHOLVWHGLQWKH''DVLQLWSDUDPHWHUVVRWKHSKUDVH
³LQLWSDUDPHWHU´PHDQV³VHUYOHWLQLWSDUDPHWHU´E\GHIDXOW
:HNQRZWKDWDVDGHYHORSHU\RX¶OOEHNLQGHUWRRWKHUVDQG
DOZD\VVD\H[SOLFLWO\ZKHWKHUDQLQLWSDUDPHWHULVDVHUYOHWLQLW
SDUDPHWHURUDFRQWH[WLQLWSDUDPHWHU
,I\RXVHH´LQLWSDUDPHWHUµZLWKRXW
NQRZLQJLILWPHDQV
VHUYOHW
RU
FRQWH[W
LQLWSDUDPHWHUDVVXPH
VHUYOHW
FRQWH[WSDUDP!
FRQWH[WSDUDP!
VHUYOHW!
VHUYOHW!
ZHEDSS!
ZHEDSS!
SDUDPQDPH!
VHUYOHWQDPH!
SDUDPQDPH!
VHUYOHWFODVV!
VHUYOHWFODVV!
SDUDPYDOXH!
SDUDPYDOXH!
IRR
FRPZLFNHGO\VPDUW%HHU7HVWHU
EDU
%HHU7HVWVHUYOHWQDPH!
2EARRANGETHEMAGNETSTOFORMA$$THATDECLARESA
PARAMETERTHATMATCHESTHESERVLETCODE
9OUWONTUSEALLOFTHEMAGNETS
.OTEWHENYOUSEEWEBAPPREMEMBERTHAT
THISISOURSHORTCUTTOSAVESPACEONTHEPAGE9OU
CANTDEPLOYAWEBXMLFILEUNLESSTHEWEBAPP
TAGHASALLTHEATTRIBUTESITNEEDS
([HUFLVH
&RGH0DJQHWV
JHW6HUYOHW&RQWH[WJHW,QLW3DUDPHWHU³IRR´
LQLWSDUDP!
LQLWSDUDP!
VHUYOHWSDUDP!
VHUYOHWSDUDP!
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
;W_PI\
MT[M
KIVaW]LW_Q\P
aW]Z;MZ^TM\+WV\M`\'
!3ERVLET#ONTEXTISA*30ORSERVLETSCONNECTION
TOBOTHTHE#ONTAINERANDTHEOTHERPARTSOFTHE
WEBAPP(EREARESOMEOFTHE3ERVLET#ONTEXT
METHODS7EPUTTHEONESYOUSHOULDKNOWFOR
THEEXAMINBOLD
Get init parameters and
get/set attributes.
Get info about the
server/container.
WeÕll talk about
RequestDispatcher later in
the chapter.
JHW,QLW3DUDPHWHU6WULQJ
JHW,QLW3DUDPHWHU1DPHV
JHW$WWULEXWH6WULQJ
JHW$WWULEXWH1DPHV
VHW$WWULEXWH6WULQJ
UHPRYH$WWULEXWH6WULQJ
JHW0DMRU9HUVLRQ
JHW6HUYHU,QIR
JHW5HDO3DWK6WULQJ
JHW5HVRXUFH$V6WUHDP6WULQJ
JHW5HTXHVW'LVSDWFKHU6WULQJ
ORJ6WULQJ
PRUHPHWKRGV
LQWHUIDFH!!
6HUYOHW&RQWH[W
Write to the serverÕs log
Þ le (vendor-speciÞ c) or
System.out.
WeÕll talk about parameters vs.
attributes in a few pages.
MDYD[VHUYOHW6HUYOHW&RQWH[W
WKH6HUYOHW&RQWH[W
6
H
U
Y
O
H
W
&
R
Q
W
H
[
W
6HUYOHW
<RXFRPSOHWHPH
%HIRUH,FDPHLQWR
\RXUOLIH\RXZHUH
MXVWDQRWKHUORVHUREMHFW
LQVWHDGRIDUHDOVHUYOHW
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
4
(OWDOALLTHEPARTSOFAWEBAPPGETACCESSTO
THEIROWN3ERVLET#ONTEXT
$
&ORSERVLETSYOUALREADYKNOWCALLYOURINHERITED
GET3ERVLET#ONTEXTMETHOD
&OR*30SITSALITTLEDIFFERENT*30SHAVESOMETHINGCALLED
hIMPLICITOBJECTSvAND3ERVLET#ONTEXTISONEOFTHEM9OULL
SEEEXACTLYHOWA*30USESA3ERVLET#ONTEXTWHENWEGET
TOTHE*30CHAPTERS
4
3OYOUGETBUILTINLOGGINGTHROUGHYOUR
CONTEXT4HATSOUNDS6%29HELPFUL
$
5MNO.OTUNLESSYOUHAVEAREALLYSMALLSIMPLE
WEBAPP4HEREAREMUCHBETTERWAYSTODOLOGGING4HE
MOSTPOPULARROBUSTLOGGINGMECHANISMIS,OGJYOU
CANFINDITONTHE!PACHESITEAT
KWWSMDNDUWDDSDFKHRUJORJM
9OUCANALSOUSETHELOGGING!0)FROMJAVAUTILLOGGING
ADDEDTO*3%INVERSION
)TSFINETOUSETHE3ERVLET#ONTEXTLOGMETHODFORSIMPLE
EXPERIMENTSBUTINAREALPRODUCTIONENVIRONMENTYOU
WILLALMOSTCERTAINLYWANTTOCHOOSESOMETHINGELSE
4HERESAGOODREFERENCEONWEBAPPLOGGINGWITHAND
WITHOUT,OGJINTHE*AVA3ERVLET*30#OOKBOOKFROM
/2EILLY
,OGGINGISNOTPARTOFTHEEXAMOBJECTIVESBUTITS
IMPORTANT&ORTUNATELYYOULLFINDTHE!0)SEASYTOUSE
$VHUYOHW¶V6HUYOHW&RQ¿JREMHFWDOZD\VKROGVDUHIHUHQFHWRWKH
6HUYOHW&RQWH[WIRUWKDWVHUYOHW6RGRQ¶WEHIRROHGLI\RXVHHVHUYOHWFRGH
RQWKHH[DPWKDWVD\V
JHW6HUYOHW&RQ¿JJHW6HUYOHW&RQWH[W
JHW,QLW3DUDPHWHU
1RWRQO\LVWKDWOHJDOEXWLWGRHVWKHVDPHWKLQJDV
WKLVJHW6HUYOHW&RQWH[WJHW,QLW3DUDPHWHU
,QDVHUYOHWWKHRQO\WLPH\RXZRXOG1(('WRJRWKURXJK\RXU
6HUYOHW&RQ¿JWRJHW\RXU6HUYOHW&RQWH[WLVLI\RX¶UHLQD6HUYOHW
FODVVWKDWGRHVQ¶WH[WHQG+WWS6HUYOHWRU*HQHULF6HUYOHWWKH
JHW6HUYOHW&RQWH[WPHWKRG\RXLQKHULWFRPHVIURP*HQHULF6HUYOHW
%XWWKHFKDQFHRI$1<21(XVLQJDQRQ+773VHUYOHWLV
ZHOODV\PSWRWLFDOO\DSSURDFKLQJ]HUR6RMXVWFDOO\RXURZQ
JHW6HUYOHW&RQWH[WPHWKRGEXWGRQ¶WEHGD]HGRUFRQIXVHGLI\RXVHH
FRGHWKDWXVHVWKH6HUYOHW&RQ¿JWRJHWWKHFRQWH[W
%XWZKDWLIWKHFRGHLVLQVLGHVRPHFODVVWKDWLV127DVHUYOHWDKHOSHU
XWLOLW\FODVVIRUH[DPSOH"6RPHRQHPLJKWKDYHSDVVHGD6HUYOHW&RQ¿J
WRWKDWFODVVDQGWKHFODVVFRGHZRXOGKDYHWRXVHJHW6HUYOHW&RQWH[W
WRJHWDUHIHUHQFHWRWKH6HUYOHW&RQWH[WREMHFW
<RXFDQJHWD6HUYOHW&RQWH[WLQWZR
GLIIHUHQWZD\V
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
+DWHWRVSRLO\RXU
6HUYOHW&RQWH[WSDUW\EXWXP
WKRVHLQLWSDUDPHWHUVFDQ·WEH
DQ\WKLQJH[FHSW675,1*67KDW·VLW
:KDWLI,ZDQWWRLQLWLDOL]HP\DSS
ZLWKDGDWDEDVH'DWD6RXUFHWKDWDOO
WKHVHUYOHWVFDQXVH"
?PI\QNaW]_IV\IVIXX
QVQ\XIZIUM\MZ\PI\¼[I
LI\IJI[M,I\I;W]ZKM'
#ONTEXTPARAMETERSCANTBEANYTHINGEXCEPT
3TRINGS!FTERALLYOUCANTVERYWELLSTUFFA$OG
OBJECTINTOAN8-,DEPLOYMENTDESCRIPTOR
!CTUALLYYOUCOULDREPRESENTASERIALIZED
OBJECTIN8-,BUTTHERESNOFACILITYFORTHISIN
THE3ERVLETSPECTODAYMAYBEINTHEFUTURE
7HATIFYOUREALLYWANTALLTHEPARTSOFYOUR
WEBAPPTOHAVEACCESSTOASHAREDDATABASE
CONNECTION9OUCANCERTAINLYPUTTHE
$ATA3OURCELOOKUPNAMEINACONTEXTINIT
PARAMETERANDTHATSPROBABLYTHEMOST
COMMONUSEOFCONTEXTPARAMETERSTODAY
"UTTHENWHODOESTHEWORKOFTURNINGTHE3TRING
PARAMETERINTOANACTUAL$ATA3OURCEREFERENCE
THATALLPARTSOFTHEWEBAPPCANSHARE
9OUCANTREALLYPUTTHATCODEINASERVLET
BECAUSEWHICHSERVLETWOULDYOUCHOOSETO
BE4HE/NE4O,OOKUP4HE$ATA3OURCE!ND
3TORE)T)N!N!TTRIBUTE$OYOUREALLYWANTTO
TRYTOGUARANTEETHATONESERVLETINPARTICULAR
WILLALWAYSRUNlRST4HINKABOUTIT
#4X3X98
+RZFRXOG\RXVROYHWKLVSUREOHP"
+RZFRXOG\RXLQLWLDOL]HDZHEDSSZLWKDQ
REMHFW"$VVXPHWKDW\RXQHHGWKH6WULQJ
FRQWH[WLQLWSDUDPHWHULQRUGHUWRFUHDWHWKDW
REMHFWWKLQNDERXWWKHGDWDEDVHH[DPSOH
FRQWH[WSDUDPHWHUOLPLWDWLRQV
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
?PI\[PMZMITTa_IV\[Q[I
TQ[\MVMZ
2KLIRQO\WKHUHZHUHDZD\
WRKDYHVRPHWKLQJOLNHD
PDLQ
PHWKRG
IRUP\ZKROHZHEDSS6RPH
FRGHWKDWDOZD\VUXQVEHIRUH$1<
VHUYOHWVRU-63V
3HEWANTSTOLISTENFORACONTEXTINITIALIZATIONEVENT
SOTHATSHECANGETTHECONTEXTINITPARAMETERSAND
RUNSOMECODEBEFORETHERESTOFTHEAPPCANSERVICEA
CLIENT
3HENEEDSSOMETHINGTHATCANBESITTINGTHERE
WAITINGTOBENOTIlEDTHATTHEAPPISSTARTINGUP
"UTWHICHPARTOFTHEAPPCOULDDOTHEWORK9OU
DONTWANTTOPICKASERVLETTHATSNOTASERVLETSJOB
4HERESNOPROBLEMINAPLAINOLDSTANDALONE*AVA
APPBECAUSEYOUVEGOTMAIN"UTWITHASERVLET
WHATDOYOUDO
9OUNEEDSOMETHINGELSE.OTASERVLETOR*30BUTSOME
OTHERKINDOF*AVAOBJECTWHOSESOLEPURPOSEINLIFE
ISTOINITIALIZETHEAPPANDPOSSIBLYTOUNINITIALIZEIT
TOOCLEANINGUPRESOURCESWHENITLEARNSOFTHEAPPS
DEMISE
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
;PM_IV\[I;MZ^TM\+WV\M`\4Q[\MVMZ
7ECANMAKEASEPARATECLASSNOTASERVLETOR*30THATCAN
LISTENFORTHETWOKEYEVENTSINA3ERVLET#ONTEXTSLIFE
INITIALIZATIONCREATIONANDDESTRUCTION4HATSEPARATECLASS
IMPLEMENTSJAVAXSERVLET3ERVLET#ONTEXT,ISTENER
*HWQRWLILHGZKHQWKHFRQWH[WLVLQLWLDOL]HGDSSLVEHLQJ
GHSOR\HG
*HWWKHFRQWH[WLQLWSDUDPHWHUVIURPWKH6HUYOHW&RQWH[W
8VHWKHLQLWSDUDPHWHUORRNXSQDPHWRPDNHDGDWDEDVH
FRQQHFWLRQ
6WRUHWKHGDWDEDVHFRQQHFWLRQDVDQDWWULEXWHVRWKDWDOO
SDUWVRIWKHZHEDSSFDQDFFHVVLW
*HWQRWLILHGZKHQWKHFRQWH[WLVGHVWUR\HGWKHDSSLV
XQGHSOR\HGRUJRHVGRZQ
&ORVHWKHGDWDEDVHFRQQHFWLRQ
:HQHHGDVHSDUDWHREMHFWWKDWFDQ
FRQWH[W,QLWLDOL]HG6HUYOHW&RQWH[W(YHQW
FRQWH[W'HVWUR\HG6HUYOHW&RQWH[W(YHQW
LQWHUIDFH!!
6HUYOHW&RQWH[W/LVWHQHU
LPSRUWMDYD[VHUYOHW
SXEOLFFODVV0\6HUYOHW&RQWH[W/LVWHQHULPSOHPHQWV
6HUYOHW&RQWH[W/LVWHQHU^
SXEOLFYRLG
FRQWH[W,QLWLDOL]HG6HUYOHW&RQWH[W(YHQWHYHQW^
FRGHWRLQLWLDOL]HWKHGDWDEDVHFRQQHFWLRQ
DQGVWRUHLWDVDFRQWH[WDWWULEXWH
`
SXEOLFYRLG
FRQWH[W'HVWUR\HG6HUYOHW&RQWH[W(YHQWHYHQW^
FRGHWRFORVHWKHGDWDEDVHFRQQHFWLRQ
`
`
A context listener
is simple: implement
ServletContextListener.
These are the two notiÞ cations
you get. Both give you a
ServletContextEvent.
$6HUYOHW&RQWH[W/LVWHQHUFODVV
ServletContextListener is in
javax.servlet package.
MDYD[VHUYOHW6HUYOHW&RQWH[W/LVWHQHU
FRQWH[WOLVWHQHUV
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
2.,KDYHDOLVWHQHUFODVV
1RZ
ZKDWGR,GR":KHUHGR,SXWWKH
FODVV":KRLQVWDQWLDWHVLW"+RZGR,
UHJLVWHUIRUWKHHYHQWV"+RZGRHV
WKHOLVWHQHUVHWWKHDWWULEXWHLQWKH
ULJKW6HUYOHW&RQWH[W"
#4X3X98
:KDWGR\RXWKLQNWKHPHFKDQLVP
PLJKWEHIRUPDNLQJDOLVWHQHUEH
SDUWRIDVSHFL¿FZHEDSS"
+LQWKRZGR\RXWHOOWKH&RQWDLQHU
DERXWWKHRWKHUSDUWVRI\RXUZHE
DSS":KHUHPLJKWWKH&RQWDLQHU
GLVFRYHU\RXUOLVWHQHU"
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
<]\WZQIT"I[QUXTM;MZ^TM\+WV\M`\4Q[\MVMZ
.OWWELLWALKTHROUGHTHESTEPSOFMAKINGANDRUNNINGA
3ERVLET#ONTEXT,ISTENER4HISISJUSTASIMPLETESTCLASSSOTHATYOU
CANSEEHOWALLTHEPIECESWORKTOGETHERWERENOTUSINGTHE
DATABASECONNECTIONEXAMPLEBECAUSEYOUDHAVETOSETUPA
DATABASETOMAKEITWORK"UTTHESTEPSARETHESAMEREGARDLESSOF
THECODEYOUPUTINYOURLISTENERCALLBACKMETHODS
)NTHISEXAMPLEWELLTURNA3TRINGINITPARAMETERINTOANACTUAL
OBJECTA$OG4HELISTENERSJOBISTOGETTHECONTEXTINITPARAMETER
FORTHEDOGSBREED"EAGLE0OODLEETCTHENUSETHAT3TRINGTO
CONSTRUCTA$OGOBJECT4HELISTENERTHENSTICKSTHE$OGOBJECTINTO
A3ERVLET#ONTEXTATTRIBUTESOTHATTHESERVLETCANRETRIEVEIT
4HEPOINTISTHATTHESERVLETNOWHASACCESSTOASHAREDAPPLICATION
OBJECTINTHISCASEA$OGANDDOESNTHAVETOREADTHECONTEXT
PARAMETERS7HETHERTHESHAREDOBJECTISA$OGORADATABASE
CONNECTIONDOESNTMATTER4HEKEYISTOUSETHEINITPARAMETERSTO
CREATEASINGLEOBJECTTHATALLPARTSOFTHEAPPWILLSHARE
7KHOLVWHQHUREMHFWDVNVWKH6HUYOHW&RQWH[W(YHQW
REMHFWIRUDUHIHUHQFHWRWKHDSS·V6HUYOHW&RQWH[W
7KHOLVWHQHUXVHVWKHUHIHUHQFHWRWKH6HUYOHW&RQWH[W
WRJHWWKHFRQWH[WLQLWSDUDPHWHUIRU´EUHHGµZKLFKLVD
6WULQJUHSUHVHQWLQJDGRJEUHHG
7KHOLVWHQHUXVHVWKDWGRJEUHHG6WULQJWRFRQVWUXFWD
'RJREMHFW
7KHOLVWHQHUXVHVWKHUHIHUHQFHWRWKH6HUYOHW&RQWH[W
WRVHWWKH'RJDWWULEXWHLQWKH6HUYOHW&RQWH[W
7KHWHVWHUVHUYOHWLQWKLVZHEDSSJHWVWKH'RJ
REMHFWIURPWKH6HUYOHW&RQWH[WDQGFDOOVWKH'RJ·V
JHW%UHHGPHWKRG
2XU'RJH[DPSOH
In this example, weÕll put a
Dog into a ServletContext.
XVLQJD6HUYOHW&RQWH[W/LVWHQHU
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
5ISQVOIVL][QVOIKWV\M`\TQ[\MVMZ
-AYBEYOURESTILLWONDERINGHOWTHE#ONTAINERDISCOVERS
ANDUSESTHELISTENER9OUCONlGUREALISTENERTHESAMEWAY
YOUTELLTHE#ONTAINERABOUTTHERESTOFYOURWEBAPPTHROUGHTHE
WEBXML$EPLOYMENT$ESCRIPTOR
7ROLVWHQIRU
6HUYOHW&RQWH[WHYHQWV
ZULWHDOLVWHQHUFODVV
WKDWLPSOHPHQWV
6HUYOHW&RQWH[W/LVWHQHU
SXWLWLQ\RXU:(%,1)
FODVVHVGLUHFWRU\DQGWHOO
WKH&RQWDLQHUE\SXWWLQJD
OLVWHQHU!HOHPHQWLQWKH
'HSOR\PHQW'HVFULSWRU
OLVWHQHU!
OLVWHQHUFODVV!
FRPH[DPSOH0\6HUYOHW&RQWH[W/LVWHQHU
OLVWHQHUFODVV!
OLVWHQHU!
&UHDWHDOLVWHQHUFODVV
FRQWH[W,QLWLDOL]HG6HUYOHW&RQWH[W(YHQW
FRQWH[W'HVWUR\HG6HUYOHW&RQWH[W(YHQW
LQWHUIDFH!!
6HUYOHW&RQWH[W/LVWHQHU
FRQWH[W,QLWLDOL]HG6HUYOHW&RQWH[W(YHQW
FRQWH[W'HVWUR\HG6HUYOHW&RQWH[W(YHQW
0\
6HUYOHW&RQWH[W/LVWHQHU
3XWWKHFODVVLQ:(%,1)FODVVHV
3XWDOLVWHQHU!HOHPHQWLQWKH
ZHE[PO'HSOR\PHQW'HVFULSWRU
:(%,1)
FODVVHV
(This isnÕt the ONLY place it can go
WEB-INF/classes is one of several
places the Container can look for
classes. WeÕll cover the others in the
Deployment chapter.)
Question for you which part of
the DD does the <listener> element
go into? Does it go into a <servlet>
element, or just under <web-app>?
Think about it.
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
?MVMML\PZMMKTI[[M[IVLWVM,,
&OROURCONTEXTLISTENERTESTEXAMPLEWENEEDTO
WRITETHECLASSESANDTHEWEBXMLlLE
&OREASEOFTESTINGWELLPUTALLOFTHECLASSES
INTHESAMEPACKAGECOMEXAMPLE
7KH6HUYOHW&RQWH[W/LVWHQHU
4HISCLASSIMPLEMENTS3ERVLET#ONTEXT,ISTENER
GETSTHECONTEXTINITPARAMETERSCREATESTHE$OG
ANDSETSTHE$OGASCONTEXTATTRIBUTE
7KHDWWULEXWHFODVV
4HE$OGCLASSISJUSTAPLAINOLD*AVACLASS
)TSJOBISTOBETHEATTRIBUTEVALUETHATTHE
3ERVLET#ONTEXT,ISTENERINSTANTIATESANDSETSIN
THE3ERVLET#ONTEXTFORTHESERVLETTORETRIEVE
7KH6HUYOHW
4HISCLASSEXTENDS(TTP3ERVLET)TSJOBISTOVERIFY
THATTHELISTENERWORKEDBYGETTINGTHE$OG
ATTRIBUTEFROMTHECONTEXTINVOKINGGET"REED
ONTHE$OGANDPRINTINGTHERESULTTOTHE
RESPONSESOWELLSEEITINTHEBROWSER
0\6HUYOHW&RQWH[W/LVWHQHUMDYD
'RJMDYD
/LVWHQHU7HVWHUMDYD
'RJ6WULQJ
JHW%UHHG
'RJ
LQWHUIDFH!!
6HUYOHW&RQWH[W/LVWHQHU
FRQWH[W,QLWLDOL]HG6HUYOHW&RQWH[W(YHQW
FRQWH[W'HVWUR\HG6HUYOHW&RQWH[W(YHQW
0\6HUYOHW&RQWH[W/LVWHQHU
+WWS6HUYOHW
*HQHULF6HUYOHW
LQWHUIDFH!!
6HUYOHW
GR*HW+WWS6HUYOHW5HTXHVW+WWS6HUYOHW5HVSRQVH
/LVWHQHU7HVWHU
6HUYOHW&RQWH[W/LVWHQHUWXWRULDO
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
?ZQ\QVO\PMTQ[\MVMZKTI[[
)TWORKSJUSTLIKEOTHERTYPESOFLISTENERSYOUMIGHT
BEFAMILIARWITHSUCHAS3WING'5)EVENTHANDLERS
2EMEMBERALLWENEEDTODOISGETTHECONTEXTINIT
PARAMETERSTOlNDOUTTHEDOGBREEDMAKETHE$OG
OBJECTANDPUTTHE$OGINTOTHECONTEXTASANATTRIBUTE
SDFNDJHFRPH[DPSOH
LPSRUWMDYD[VHUYOHW
SXEOLFFODVV0\6HUYOHW&RQWH[W/LVWHQHULPSOHPHQWV
6HUYOHW&RQWH[W/LVWHQHU^
SXEOLFYRLG
FRQWH[W,QLWLDOL]HG6HUYOHW&RQWH[W(YHQWHYHQW^
6HUYOHW&RQWH[WVF HYHQWJHW6HUYOHW&RQWH[W
6WULQJGRJ%UHHG VFJHW,QLW3DUDPHWHU³EUHHG´
'RJG QHZ'RJGRJ%UHHG
VFVHW$WWULEXWH³GRJ´G
`
SXEOLFYRLG
FRQWH[W'HVWUR\HG6HUYOHW&RQWH[W(YHQWHYHQW^
QRWKLQJWRGRKHUH
`
`
Implement javax.servlet.ServletContextListener.
Ask the event for the ServletContext.
Use the context to get
the init parameter.
Make a new Dog.
Use the context to set an attribute (a
name/object pair) that is the Dog. Now
other parts of the app will be able to get
the value of the attribute (the Dog).
We donÕt need anything here. The Dog
doesnÕt need to be cleaned up when the
context goes away, it means the whole
app is going down, including the Dog.
LQWHUIDFH!!
6HUYOHW&RQWH[W/LVWHQHU
FRQWH[W,QLWLDOL]HG6HUYOHW&RQWH[W(YHQW
FRQWH[W'HVWUR\HG6HUYOHW&RQWH[W(YHQW
0\6HUYOHW&RQWH[W/LVWHQHU
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
?ZQ\QVO\PMI\\ZQJ]\MKTI[[,WO
/HYEAHWENEEDA$OGCLASSTHECLASSREPRESENTING
THEOBJECTWEREGOINGTOSTOREINTHE3ERVLET#ONTEXT
AFTERREADINGTHECONTEXTINITPARAMETERS
SDFNDJHFRPH[DPSOH
SXEOLFFODVV'RJ^
SULYDWH6WULQJEUHHG
SXEOLF'RJ6WULQJEUHHG^
WKLVEUHHG EUHHG
`
SXEOLF6WULQJJHW%UHHG^
UHWXUQEUHHG
`
`
Nothing special here.
Just a plain old Java class.
4
)THOUGHT)READSOMEWHERETHATSERVLETATTRIBUTES
HADTOBE3ERIALIZABLE
$
)NTERESTINGQUESTION4HEREARESEVERALDIFFERENT
ATTRIBUTETYPESANDWHETHERTHEATTRIBUTESHOULDBE
3ERIALIZABLEONLYMATTERSWITH3ESSIONATTRIBUTES!NDTHE
SCENARIOINWHICHITMATTERSISONLYIFTHEAPPLICATIONIS
DISTRIBUTEDACROSSMORETHANONE*6-7ELLTALKALLABOUTTHAT
INTHE3ESSIONSCHAPTER
4HERESNOTECHNICALNEEDTOHAVEANYATTRIBUTESINCLUDING
3ESSIONATTRIBUTESBE3ERIALIZABLEALTHOUGHYOUMIGHT
CONSIDERMAKINGALLOFYOURATTRIBUTES3ERIALIZABLEBYDEFAULT
UNLESSYOUHAVEAREALLYGOODREASON./4TO
4HINKABOUTITAREYOUREALLYCERTAINTHATNOBODYWILLEVER
WANTTOUSEOBJECTSOFTHATTYPEASARGUMENTSORRETURNVALUES
ASPARTOFAREMOTEMETHODCALL#ANYOUREALLYGUARANTEETHAT
ANYONEWHOUSESTHISCLASS$OGINTHISCASEWILLNEVERRUNIN
ADISTRIBUTEDENVIRONMENT
3OALTHOUGHYOUARENTREQUIREDTOMAKEANYATTRIBUTES
3ERIALIZABLEYOUPROBABLYSHOULDIFYOUCAN
(WeÕll use the context init
parameter as the argument for
the Dog constructor.)
Our servlet will get the Dog from the
context (the Dog that the listener sets
as an attribute), call the DogÕs getBreed()
method, and print out the breed in the
response so we can see it in the browser.
WKHDWWULEXWHFODVV
'RJ6WULQJ
JHW%UHHG
'RJ
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
?ZQ\QVO\PM[MZ^TM\KTI[[
4HISISTHECLASSTHATTESTSTHE
3ERVLET#ONTEXT,ISTENER)FEVERYTHINGIS
WORKINGRIGHTBYTHETIMETHE3ERVLETS
DO'ETMETHODRUNSFORTHElRSTTIMETHE
$OGWILLBEWAITINGASANATTRIBUTEINTHE
3ERVLET#ONTEXT
SDFNDJHFRPH[DPSOH
LPSRUWMDYD[VHUYOHW
LPSRUWMDYD[VHUYOHWKWWS
LPSRUWMDYDLR
SXEOLFFODVV/LVWHQHU7HVWHUH[WHQGV+WWS6HUYOHW^
SXEOLFYRLGGR*HW+WWS6HUYOHW5HTXHVWUHTXHVW+WWS6HUYOHW5HVSRQVHUHVSRQVH
WKURZV,2([FHSWLRQ6HUYOHW([FHSWLRQ^
UHVSRQVHVHW&RQWHQW7\SH³WH[WKWPO´
3ULQW:ULWHURXW UHVSRQVHJHW:ULWHU
RXWSULQWOQ³WHVWFRQWH[WDWWULEXWHVVHWE\OLVWHQHUEU!´
RXWSULQWOQ³EU!´
'RJGRJ 'RJJHW6HUYOHW&RQWH[WJHW$WWULEXWH³GRJ´
RXWSULQWOQ³'RJ¶VEUHHGLV³
GRJJHW%UHHG
`
`
Nothing special so far
just a regular servlet.
Now we get the Dog from
the ServletContext. If
the listener worked, the
Dog will be there BEFORE
this service method is
called for the Þ rst time.
If things didnÕt work, THIS is where
weÕll Þ nd out weÕll get a big fat
NullPointerException if we try to call
getBreed() and thereÕs no Dog.
donÕt forget the cast!!
%XWJHW,QLW3DUDPHWHUUHWXUQVD6WULQJ6R\RX
PXVWFDVWWKHUHWXUQRIJHW$WWULEXWHEXWWKH
UHWXUQRIJHW,QLW3DUDPHWHUFDQEHDVVLJQHG
GLUHFWO\WRD6WULQJ6RGRQ¶WEHIRROHGE\EDG
H[DPFRGHWKDWGRHVQ¶WXVHDFDVW
'RJG FW[JHW$WWULEXWH³GRJ´
$VVXPHFW[LVD6HUYOHW&RQWH[W
JHW$WWULEXWHUHWXUQV
W\SH2EMHFW<RXQHHG
WRFDVWWKHUHWXUQ
+WWS6HUYOHW
GR*HW+WWS6HUYOHW5HTXHVW+WWS6HUYOHW5HVSRQVH
/LVWHQHU7HVWHU
Bad!!
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
?ZQ\QVO\PM,MXTWaUMV\,M[KZQX\WZ
.OWWETELLTHE#ONTAINERTHATWEHAVEALISTENERFOR
THISAPPUSINGTHELISTENERELEMENT4HISELEMENTIS
SIMPLEITNEEDSONLYTHECLASSNAME4HATSIT
ZHEDSS[POQV ´KWWSMDYDVXQFRP[POQVMHH´
[POQV[VL ´KWWSZZZZRUJ;0/6FKHPDLQVWDQFH´
[VLVFKHPD/RFDWLRQ ´KWWSMDYDVXQFRP[POQVMHHZHEDSSBB[VG´
YHUVLRQ ´´!
VHUYOHW!
VHUYOHWQDPH!/LVWHQHU7HVWHUVHUYOHWQDPH!
VHUYOHWFODVV!FRPH[DPSOH/LVWHQHU7HVWHUVHUYOHWFODVV!
VHUYOHW!
VHUYOHWPDSSLQJ!
VHUYOHWQDPH!/LVWHQHU7HVWHUVHUYOHWQDPH!
XUOSDWWHUQ!/LVWHQ7HVWGRXUOSDWWHUQ!
VHUYOHWPDSSLQJ!
FRQWH[WSDUDP!
SDUDPQDPH!EUHHGSDUDPQDPH!
SDUDPYDOXH!*UHDW'DQHSDUDPYDOXH!
FRQWH[WSDUDP!
OLVWHQHU!
OLVWHQHUFODVV!
FRPH[DPSOH0\6HUYOHW&RQWH[W/LVWHQHU
OLVWHQHUFODVV!
OLVWHQHU!
ZHEDSS!
We need a context init parameter
for the app. The listener needs this
to construct the Dog.
Register this class as a listener. IMPORTANT:
the <listener> element does NOT go
inside a <servlet> element. That wouldnÕt
work because a context listener is for a
ServletContext (which means application-
wide) event. The whole point is to initialize
the app BEFORE any servlets are initialized.
This is the web.xml Þ le
inside the WEB-INF
directory for this web app.
"[POYHU
VLRQ ´´
HQFRGLQJ
´87)´"!
'2&7<3(
ZHE[PO
FRQ¿JXULQJDOLVWHQHULQWKH''
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
WKHUH DUH QR
'
XPE 4XHVWLRQV
4
(OLDONHOWAREYOUTELLINGTHE#ONTAINER
THATTHISISALISTENERFOR3ERVLET#ONTEXTEVENTS4HERE
DOESNTSEEMTOBEAN8-,ELEMENTFORLISTENERTYPE
ORANYTHINGTHATSAYSWHATTYPEOFEVENTSTHISLISTENER
ISFOR"UT)NOTICEDYOUHAVEh3ERVLET#ONTEXT,ISTENERv
ASPARTOFTHECLASSNAMEISTHATHOWTHE#ONTAINER
KNOWS"YTHENAMINGCONVENTION
$
.O4HERESNONAMINGCONVENTION7EJUSTDIDIT
THATWAYTOMAKEITPAINFULLYCLEARWHATKINDOFACLASSWE
WROTE4HE#ONTAINERFIGURESITOUTSIMPLYBYINSPECTING
THECLASSANDNOTICINGTHELISTENERINTERFACEORINTERFACES
ALISTENERCANIMPLEMENTMORETHANONELISTENERINTER
FACE
4
$OESTHATMEANTHEREAREOTHERTYPESOFLISTEN
ERSINTHESERVLET!0)
$
9ESTHEREARESEVERALOTHERTYPESOFLISTENERSTHAT
WELLTALKABOUTINAMINUTE
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
FKDSWHU
+WUXQTMIVLLMXTWa
,ETSGETITALLWORKING4HESTEPSARE
7KH\¶UHDOOLQWKHVDPHSDFNDJH
&RPSLOHWKHWKUHHFODVVHV
&UHDWHDQHZZHEDSSLQ7RPFDW
N &UHDWHDGLUHFWRU\QDPHGOLVWHQHU7HVWDQGSODFHLW
LQVLGHWKH7RPFDWZHEDSSVGLUHFWRU\
N &UHDWHDGLUHFWRU\QDPHG:(%,1)DQGSODFHLW
LQVLGHWKHOLVWHQHU7HVWGLUHFWRU\
N 3XW\RXUZHE[PO¿OHLQWKH:(%,1)GLUHFWRU\
N 0DNHDFODVVHVGLUHFWRU\LQVLGH:(%,1)
N 0DNHDGLUHFWRU\VWUXFWXUHLQVLGHFODVVHVWKDW
PDWFKHV\RXUSDFNDJHVWUXFWXUHDGLUHFWRU\FDOOHG
FRPWKDWFRQWDLQVH[DPSOH
&RS\\RXUWKUHHFRPSLOHGÀOHVLQWR\RXUZHE
DSSGLUHFWRU\VWUXFWXUHLQ7RPFDW
OLVWHQHU7HVW:(%,1)FODVVHVFRPH[DPSOH'RJFODVV
OLVWHQHU7HVW:(%,1)FODVVHVFRPH[DPSOH/LVWHQHU7HVWHUFODVV
OLVWHQHU7HVW:(%,1)FODVVHVFRPH[DPSOH0\6HUYOHW&RQWH[W/LVWHQHUFODVV
:(%,1)
FODVVHV
OLVWHQHU7HVW
FRP
H[DPSOH
'RJFODVV
0\6HUYOHW&RQWH[W/LVWHQHUFODVV
/LVWHQHU7HVWHUFODVV
"[POYHU
VLRQ ´´
HQFRGLQJ
´87)´"!
'2&7<3(
ZHE[PO
The root of this web app.
This directory must be inside
TomcatÕs ÒwebappsÓ directory.
ZHEDSSV
WRPFDW
Remember: ALL your web apps
go in here (each with its own
directory structure).
3XW\RXUZHE[PO'HSOR\PHQW'HVFULSWRULQWR
WKH:(%,1)GLUHFWRU\IRUWKLVZHEDSS
OLVWHQHU7HVW:(%,1)ZHE[PO
'HSOR\WKHDSSE\VKXWWLQJGRZQDQG
UHVWDUWLQJ7RPFDW
FRPSLOLQJDQGGHSOR\LQJWKHOLVWHQHUWHVW
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
DWWULEXWHVDQGOLVWHQHUV
\RXDUHKHUH
<ZaQ\W]\
"RINGUPYOURBROWSERANDLETSHITTHESERVLETDIRECTLY7EDIDNT
BOTHERMAKINGAN(4-,PAGESOWELLACCESSTHESERVLETBYTYPING
INTHE52,FROMTHESERVLETMAPPINGINTHE$$,ISTEN4ESTDO
KWWSORFDOKRVWOLVWHQHU7HVW/LVWHQ7HVWGR
WHVWFRQWH[WDWWULEXWHVVHWE\OLVWHQHU
'RJ·VEUHHGLV*UHDW'DQH
<ZW]JTM[PWW\QVO
)FYOUGETA.ULL0OINTER%XCEPTIONYOUDIDNTGETA$OGBACK
FROMGET!TTRIBUTE#HECKTHE3TRINGNAMEUSEDINSET!TTRIBUTE
ANDMAKESUREITMATCHESTHE3TRINGNAMEYOUREUSINGIN
GET!TTRIBUTE
2ECHECKYOURWEBXMLANDMAKESURETHELISTENERISREGISTERED
4RYLOOKINGATTHESERVERLOGSANDSEEIFYOUCANlNDOUTIFTHE
LISTENERISACTUALLYBEINGCALLED
4OMAKEITASCONFUSINGASPOSSIBLEWEGAVEEVERYTHINGASUBTLY
DIFFERENTNAME7EWANTTOMAKESUREYOUREPAYINGATTENTIONTO
HOWTHESENAMESAREUSEDANDWHENYOUNAMEEVERYTHINGTHE
SAMEITSTOUGHTOTELLHOWTHENAMESAFFECTYOURAPP
3ERVLETCLASSNAME,ISTENER4ESTERCLASS
7EBAPPDIRECTORYNAMELISTENER4EST
52,PATTERNMAPPEDTOTHISTHESERVLET,ISTEN4ESTDO
Be careful about whether itÕs
Listener or Listen, Tester or Test.
It must have worked! The servlet
called a method on the Dog attribute
that was set by the listener.
Chapter 5. Being a Web App
Chapter 5. Being a Web App
Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham ISBN: 0596005407 Publisher: O'Reilly Prepared for Stephen Goss, Safari ID:
Print Publication Date: 8/1/2004 User number: 747221 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.