Sie sind auf Seite 1von 8

30/5/2015

WARFilesandDeploymentLearningJava,4thEdition

Learning Java, 4th Edition

Topics

Feedback(http://community.safaribooksonline.com/)

NEXT

PREV

Java Web Applicat

Servlet Filters

WAR Files and Deployment


Aswedescribedintheintroductiontothischapter,aWARfileisanarchive
thatcontainsallthepartsofawebapplication:Javaclassfilesforservletsand
webservices,JSPs,HTMLpages,images,andotherresources.TheWARfileis
simplyaJARfile(whichisitselfafancyZIPfile)withspecifieddirectoriesfor
theJavacodeandonedesignatedconfigurationfile:theweb.xmlfile,which
tellstheapplicationserverwhattorunandhowtorunit.WARfilesalways
havetheextension.war,buttheycanbecreatedandreadwiththestandardjar
tool.
ThecontentsofatypicalWARmightlooklikethis,asrevealedbythejartool:

Unlock the rest of Learning Java, 4th


Edition and 30,000 other books and
videos
Choose a Username
Your Email Address

$jartvfshoppingcart.war
index.html
purchase.html
receipt.html
images/happybunny.gif
WEBINF/web.xml
WEBINF/classes/com/mycompany/PurchaseServlet.class
WEBINF/classes/com/mycompany/ReturnServlet.class
WEBINF/lib/thirdparty.jar

StartaFree
Whendeployed,thenameoftheWARbecomes,bydefault,therootpathofthe
10DayTrial
webapplicationinthiscase,shoppingcart.Thus,thebaseURLforthisweb

Choose a Password

app,ifdeployedonhttp://www.oreilly.com,is

Learn about
http://www.oreilly.com/shoppingcart/,andallreferencestoitsdocuments,
Safari forimages,andservletsstartwiththatpath.ThetopleveloftheWARfilebecomes
Businessthedocumentroot(basedirectory)forservingfiles.Ourindex.htmlfileappears
atthebaseURLwejustmentioned,andourhappybunny.gifimageisreferenced

Have an account?
ashttp://www.oreilly.com/shoppingcart/images/happybunny.gif.
Sign in.

TheWEBINFdirectory(allcaps,hyphenated)isaspecialdirectorythat
containsalldeploymentinformationandapplicationcode.Thisdirectoryis
protectedbythewebserver,anditscontentsarenotvisibletooutsideusersof
theapplication,evenifyouaddWEBINFtothebaseURL.Yourapplication
classescanloadadditionalfilesfromthisareausinggetResource()onthe
servletcontext,however,soitisasafeplacetostoreapplicationresources.The
WEBINFdirectoryalsocontainstheweb.xmlfile,whichwelltalkmoreabout
inthenextsection.
TheWEBINF/classesandWEBINF/libdirectoriescontainJavaclassfilesand
JARlibraries,respectively.TheWEBINF/classesdirectoryisautomatically
addedtotheclasspathofthewebapplication,soanyclassfilesplacedhere
(usingthenormalJavapackageconventions)areavailabletotheapplication.
Afterthat,anyJARfileslocatedinWEBINF/libareappendedtothewebapps
classpath(theorderinwhichtheyareappendedis,unfortunately,not
specified).Youcanplaceyourclassesineitherlocation.Duringdevelopment,
itisofteneasiertoworkwiththelooseclassesdirectoryandusethelib
directoryforsupportingclassesandthirdpartytools.Itsalsopossibleto
installJARfilesdirectlyintheservletcontainertomakethemavailabletoall
webappsrunningonthatserver.Thisisoftendoneforcommonlibrariesthat
willbeusedbymanywebapps.Thelocationforplacingthelibraries,however,
isnotstandardandanyclassesthataredeployedinthiswaycannotbe
automaticallyreloadedifchangedafeatureofWARfilesthatwelldiscuss
later.ServletAPIrequiresthateachserverprovideadirectoryforthese
extensionJARsandthattheclassestherewillbeloadedbyasingleclassloader
andmadevisibletothewebapplication.

Configuration with web.xml and Annotations


Theweb.xmlfileisanXMLconfigurationfilethatlistsservletsandrelated
entitiestobedeployed,therelativenames(URLpaths)underwhichtodeploy
them,theirinitializationparameters,andtheirdeploymentdetails,including
securityandauthorization.FormostofthehistoryofJavawebapplications,
thiswastheonlydeploymentconfigurationmechanism.However,asofthe

https://www.safaribooksonline.com/library/view/learningjava4th/9781449372477/ch15s03.html

1/8

30/5/2015

WARFilesandDeploymentLearningJava,4thEdition

Servlet3.0API,thereareadditionaloptions.Mostconfigurationcannowbe
doneusingJavaannotations.WesawtheWebServletannotationusedinthe
firstexample,HelloClient,todeclaretheservletandspecifyitsdeployment
URLpath.Usingtheannotation,wecoulddeploytheservlettotheTomcat
serverwithoutanyweb.xmlfile.AnotheroptionwiththeServlet3.0APIisto
deployservletprocedurallyusingJavacodeatruntime.
InthissectionwewilldescribeboththeXMLandannotationstyleof
configuration.Formostpurposes,youwillfinditeasiertousetheannotations,
butthereareacoupleofreasonstounderstandtheXMLconfigurationaswell.
First,theweb.xmlcanbeusedtooverrideorextendthehardcodedannotation
configuration.UsingtheXML,youcanchangeconfigurationatdeployment
timewithoutrecompilingtheclasses.Ingeneral,configurationintheXML
willtakeprecedenceovertheannotations.Itisalsopossibletotelltheserverto
ignoretheannotationscompletely,usinganattributecalledmetadata
completeintheweb.xml.Next,theremaybesomeresidualconfiguration,
especiallyrelatingtooptionsoftheservletcontainer,whichcanonlybedone
throughXML.
WewillassumethatyouhaveatleastapassingfamiliaritywithXML,butyou
cansimplycopytheseexamplesinacutandpastefashion.(Fordetailsabout
workingwithJavaandXML,seeChapter24.)Letsstartwithasimpleweb.xml
fileforourHelloClientservletexample.Itlookslikethis:

<webapp>
<servlet>
<servletname>helloclient1</servletname>
<servletclass>HelloClient</servletclass>
</servlet>
<servletmapping>
<servletname>helloclient1</servletname>
<urlpattern>/hello</urlpattern>
</servletmapping>
</webapp>

Thetoplevelelementofthedocumentiscalled<webapp>.Manytypesof
entriesmayappearinsidethe<webapp>,butthemostbasicare<servlet>
declarationsand<servletmapping>deploymentmappings.The
<servlet>declarationtagisusedtodeclareaninstanceofaservletand,
optionally,togiveitinitializationandotherparameters.Oneinstanceofthe
servletclassisinstantiatedforeach<servlet>tagappearingintheweb.xml
file.
Atminimum,the<servlet>declarationrequirestwopiecesofinformation:a
<servletname>,whichservesasahandletoreferencetheservletelsewhere
intheweb.xmlfile,andthe<servletclass>tag,whichspecifiestheJava
classnameoftheservlet.Here,wenamedtheservlethelloclient1.We
nameditlikethistoemphasizethatwecoulddeclareotherinstancesofthe
sameservletifwewantedto,possiblygivingthemdifferentinitialization
parameters,etc.Theclassnameforourservletis,ofcourse,HelloClient.Ina
realapplication,theservletclasswouldlikelyhaveafullpackagename,such
ascom.oreilly.servlets.HelloClient.
Aservletdeclarationmayalsoincludeoneormoreinitializationparameters,
whicharemadeavailabletotheservletthroughtheServletConfigobjects
getInitParameter()method:

<servlet>
<servletname>helloclient1</servletname>
<servletclass>HelloClient</servletclass>
<initparam>
<paramname>foo</paramname>
<paramvalue>bar</paramvalue>
</initparam>
</servlet>

Next,wehaveour<servletmapping>,whichassociatestheservletinstance
withapathonthewebserver:

<servletmapping>
<servletname>helloclient1</servletname>
<urlpattern>/hello</urlpattern>
</servletmapping>

Herewemappedourservlettothepath/hello.(Wecouldincludeadditional
urlpatternsinthemappingifdesired.)IfwelaternameourWAR
learningjava.waranddeployitonwww.oreilly.com,thefullpathtothisservlet
wouldbehttp://www.oreilly.com/learningjava/hello.Justaswecoulddeclare
morethanoneservletinstancewiththe<servlet>tag,wecoulddeclaremore
thanone<servletmapping>foragivenservletinstance.Wecould,for
example,redundantlymapthesamehelloclient1instancetothepaths
/helloand/hola.The<urlpattern>tagprovidessomeveryflexiblewaysto
specifytheURLsthatshouldmatchaservlet.Welltalkaboutthisindetailin
thenextsection.
Finally,weshouldmentionthatalthoughtheweb.xmlexamplelistedearlier
willworkonsomeapplicationservers,itistechnicallyincompletebecauseitis
missingformalinformationthatspecifiestheversionofXMLitisusingand
theversionoftheweb.xmlfilestandardwithwhichitcomplies.Tomakeit

https://www.safaribooksonline.com/library/view/learningjava4th/9781449372477/ch15s03.html

2/8

30/5/2015

WARFilesandDeploymentLearningJava,4thEdition

fullycompliantwiththestandards,addalinesuchas:

<?xmlversion="1.0"encoding="ISO88591"?>

AsofServletAPI2.5,theweb.xmlversioninformationtakesadvantageofXML
Schemas.(WelltalkaboutXMLDTDsandXMLSchemasinChapter24.)The
additionalinformationisinsertedintothe<webapp>element:
<webapp
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/webapp_2_5.xsd
version=2.5>

Ifyouleavethemout,theapplicationmaystillrun,butitwillbeharderforthe
servletcontainertodetecterrorsinyourconfigurationandgiveyouclearerror
messages.
Theequivalentoftheprecedingservletdeclarationandmappingis,aswesaw
earlier,ouronelineannotation:

@WebServlet(urlPatterns={"/hello","/hola"})
publicclassHelloClientextendsHttpServlet{
...
}

HeretheWebServletattributeurlPatternsallowsustospecifyoneormore
URLpatternsthataretheequivalenttotheurlpatterndeclarationinthe
web.xml.

URL Pattern Mappings


The<urlpattern>specifiedinthepreviousexamplewasasimplestring,
/hello.Forthispattern,onlyanexactmatchofthebaseURLfollowedby
/hellowouldinvokeourservlet.The<urlpattern>tagiscapableofmore
powerfulpatterns,however,includingwildcards.Forexample,specifyinga
<urlpattern>of/hello*allowsourservlettobeinvokedbyURLssuch
ashttp://www.oreilly.com/learningjava/helloworldor.../hellobaby.You
canevenspecifywildcardswithextensions(e.g.,*.htmlor*.foo,meaning
thattheservletisinvokedforanypaththatendswiththosecharacters).
Usingwildcardscanresultinmorethanonematch.ConsiderURLsendingin
/scooby*and/scoobydoo*.WhichshouldbematchedforaURLendingin
.../scoobydoobiedoo?Whatifwehaveathirdpossiblematchbecauseofa
wildcardsuffixextensionmapping?Therulesforresolvingtheseareas
follows.
First,anyexactmatchistaken.Forexample,/hellomatchesthe/helloURL
patterninourexampleregardlessofanyadditional/hello*.Failingthat,the
containerlooksforthelongestprefixmatch.So/scoobydoobiedoomatches
thesecondpattern,/scoobydoo*,becauseitislongerandpresumablymore
specific.Failinganymatchesthere,thecontainerlooksatwildcardsuffix
mappings.Arequestendingin.foomatchesa*.foomappingatthispointin
theprocess.Finally,failinganymatchesthere,thecontainerlooksforadefault,
catchallmappingnamed/*.Aservletmappedto/*picksupanything
unmatchedbythispoint.Ifthereisnodefaultservletmapping,therequestfails
witha404notfoundmessage.

Deploying HelloClient
OnceyouvedeployedtheHelloClientservlet,itshouldbeeasytoadd
examplestotheWARasyouworkwiththeminthischapter.Inthissection,
wellshowyouhowtobuildaWARbyhand.InBuildingWARFileswith
Antlaterinthischapter,wellshowamorerealisticwaytomanageyour
applicationsusingthepopularbuildtool,Ant.Youcanalsograbthefullsetof
examples,alongwiththeirsourcecode,inthelearningjava.warfilefromthis
bookswebsiteathttp://oreil.ly/Java_4E (http://oreil.ly/Java_4E).
TocreatetheWARbyhand,wefirstcreatetheWEBINFandWEBINF/classes
directories.Ifyouareusingaweb.xmlfile,placeitintoWEBINF.Putthe
HelloClient.classintoWEBINF/classes.Usethejarcommandtocreate
learningjava.war(WEBINFatthetoplevelofthearchive):

$jarcvflearningjava.warWEBINF

YoucanalsoincludedocumentsandotherresourcesintheWARbyadding
theirnamesaftertheWEBINFdirectory.Thiscommandproducesthefile
learningjava.war.Youcanverifythecontentsusingthejarcommand:
$jartvflearningjava.war
document1.html
WEBINF/web.xml
WEBINF/classes/HelloClient.class

NowallthatisnecessaryistodroptheWARintothecorrectlocationforyour
server.Ifyouhavenotalready,youshoulddownloadandinstallApache
Tomcat.ThelocationforWARfilesisthewebappsdirectorywithinyour

https://www.safaribooksonline.com/library/view/learningjava4th/9781449372477/ch15s03.html

3/8

30/5/2015

WARFilesandDeploymentLearningJava,4thEdition

Tomcatinstallationdirectory.PlaceyourWARhere,andstarttheserver.If
Tomcatisconfiguredwiththedefaultportnumber,youshouldbeabletopoint
totheHelloClientservletwithoneoftwoURLs:
http://localhost:8080/learningjava/helloor
http://<yourserver>:8080/learningjava/hello,where<yourserver>isthe
nameorIPaddressofyourserver.Ifyouhavetrouble,lookinthelogsdirectory
oftheTomcatfolderforerrors.

Reloading web apps


AllservletcontainersaresupposedtoprovideafacilityforreloadingWAR
filesmanysupportreloadingofindividualservletclassesaftertheyhavebeen
modified.ReloadingWARsispartoftheservletspecificationandisespecially
usefulduringdevelopment.Supportforreloadingwebappsvariesfromserver
toserver.Normally,allthatyouhavetodoisdropanewWARinplaceofthe
oldoneintheproperlocation(e.g.,thewebappsdirectoryforTomcat)andthe
containershutsdowntheoldapplicationanddeploysthenewversion.This
worksinTomcatwhentheautoDeployattributeisset(itisonbydefault)
andalsoinBEAsWebLogicapplicationserverwhenitisconfiguredin
developmentmode.
Someservers,includingTomcat,explodeWARsbyunpackingthemintoa
directoryunderthewebappsdirectory,ortheyallowyouexplicitlyto
configurearootdirectory(orcontext)foryourunpackedwebappthrough
theirownconfigurationfiles.Inthismode,theymayallowyoutoreplace
individualfiles,whichcanbeespeciallyusefulfortweakingHTMLorJSPs.
TomcatautomaticallyreloadsWARfileswhentheychangethem(unless
configurednotto),soallyouhavetodoisdropanupdatedWARovertheold
oneanditwillredeployitasnecessary.Insomecases,itmaybenecessaryto
restarttheservertomakeallchangestakeeffect.Whenindoubt,shutdownand
restart.
TomcatalsoprovidesaclientsidedeployerpackagethatintegrateswithAnt
toautomatebuilding,deploying,andredeployingapplications.Welldiscuss
Antlaterinthischapter.

Error and Index Pages


Oneofthefinerpointsofwritingaprofessionallookingwebapplicationis
takingcaretohandleerrorswell.Nothingannoysausermorethangettinga
funnylookingpagewithsometechnicalmumbojumboerrorinformationonit
whenheexpectedthereceiptforhisChristmaspresent.Throughtheweb.xml
file,itispossibletospecifydocumentsorservletstohandleerrorpagesthatare
shownforvariousconditions,aswellasthespecialcaseofwelcomefiles
(indexfiles)thatareinvokedforpathscorrespondingtodirectories.Atthis
time,thereisnocorrespondingwaytodeclareerrorpagesorwelcomefiles
usingannotations.
YoucandesignateapageorservletthatcanhandlevariousHTTPerrorstatus
codes,suchas404NotFoundand403Forbidden,usingoneormore
<errorpage>declarations:
<webapp>
...
<errorpage>
<errorcode>404</errorcode>
<location>/notfound.html</location>
</errorpage>
<errorpage>
<errorcode>403</errorcode>
<location>/secret.html</location>
</errorpage>

Additionally,youcandesignateerrorpagesbasedonJavaexceptiontypesthat
maybethrownfromtheservlet.Forexample:

<errorpage>
<exceptiontype>java.lang.IOException</exceptiontype>
<location>/ioexception.html</location>
</errorpage>

ThisdeclarationcatchesanyIOExceptionsgeneratedfromservletsintheweb
appanddisplaystheioexception.htmlpage.Ifnomatchingexceptionsare
foundinthe<errorpage>declarations,andtheexceptionisoftype
ServletException(orasubclass),thecontainermakesasecondtrytofind
thecorrecthandler.Itlooksforawrappedexception(thecauseexception)
containedintheServletExceptionandattemptstomatchittoanerrorpage
declaration.
IntheServlet3.0API,youcanalsodesignateacatchallerrorpagethatwill
handleanyunhandlederrorcodesandexceptiontypesasfollows:
<errorpage>
<location>/anyerror.html</location>
</errorpage>

Aswevementioned,youcanuseaservlettohandleyourerrorpages,justas
youcanuseastaticdocument.Infact,thecontainersuppliesseveralhelpful
piecesofinformationtoanerrorhandlingservlet,whichtheservletcanusein
generatingaresponse.Theinformationismadeavailableintheformofservlet

https://www.safaribooksonline.com/library/view/learningjava4th/9781449372477/ch15s03.html

4/8

30/5/2015

WARFilesandDeploymentLearningJava,4thEdition

requestattributesthroughthemethodgetAttribute():

ObjectrequestAttribute=servletRequest.getAttribute("name");

Attributesarelikeservletparameters,exceptthattheycanbearbitraryobjects.
WehaveseenattributesoftheServletContextinTheServletContextAPI
section.Inthiscase,wearetalkingaboutattributesoftherequest.Whena
servlet(orJSPorfilter)isinvokedtohandleanerrorcondition,thefollowing
stringattributesaresetintherequest:
javax.servlet.error.servlet_name
javax.servlet.error.request_uri
javax.servlet.error.message

Dependingonwhetherthe<errorpage>declarationwasbasedonan
<errorcode>or<exceptiontype>condition,therequestalsocontains
oneofthefollowingtwoattributes:
//statuscodeIntegerorExceptionobject
javax.servlet.error.status_code
javax.servlet.error.exception

Inthecaseofastatuscode,theattributeisanIntegerrepresentingthecode.
Inthecaseoftheexceptiontype,theobjectistheactualinstigatingexception.
Indexesfordirectorypathscanbedesignatedinasimilarway.Normally,when
auserspecifiesadirectoryURLpath,thewebserversearchesforadefaultfile
inthatdirectorytobedisplayed.Themostcommonexampleofthisisthe
ubiquitousindex.htmlfile.Youcandesignateyourownorderedlistoffilesto
lookforbyaddinga<welcomefilelist>entrytoyourweb.xmlfile.For
example:

<welcomefilelist>
<welcomefile>index.html</welcomefile>
<welcomefile>index.htm</welcomefile>
</welcomefilelist>

<welcomefilelist>specifiesthatwhenapartialrequest(directorypath)
isreceived,theservershouldsearchfirstforafilenamedindex.htmland,ifthat
isnotfound,afilecalledindex.htm.Ifnoneofthespecifiedwelcomefilesis
found,itisleftuptotheservertodecidewhatkindofpagetodisplay.Servers
aregenerallyconfiguredtodisplayadirectorylikelistingortoproducean
errormessage.

Security and Authentication


OneofthemostpowerfulfeaturesofwebappdeploymentwiththeServletAPI
istheabilitytodefinedeclarativesecurityconstraints,meaningthatyoucan
spelloutintheweb.xmlfileexactlywhichareasofyourwebapp(URLpathsto
documents,directories,servlets,etc.)areloginprotected,thetypesofusers
allowedaccesstothem,andtheclassofsecurityprotocolrequiredfor
communications.Itisnotnecessarytowritecodeinyourservletstoimplement
thesebasicsecurityprocedures.
Therearetwotypesofentriesintheweb.xmlfilethatcontrolsecurityand
authentication.Firstarethe<securityconstraint>entries,whichprovide
authorizationbasedonuserrolesandsecuretransportofdata,ifdesired.
Secondisthe<loginconfig>entry,whichdeterminesthekindof
authenticationusedforthewebapplication.

Protecting Resources with Roles


Letstakealookatasimpleexample.Thefollowingweb.xmlexcerptdefinesan
areacalledSecretdocumentswithaURLpatternof/secret/*anddesignates
thatonlyuserswiththerolesecretagentmayaccessthem.Itspecifiesthe
simplestformofloginprocess:theBASICauthenticationmodel,whichcauses
thebrowsertoprompttheuserwithasimplepopupusernameandpassword
dialogbox:

<webapp>
...
<securityconstraint>
<webresourcecollection>
<webresourcename>Secretdocuments</webresourcename>
<urlpattern>/secret/*</urlpattern>
</webresourcecollection>
<authconstraint>
<rolename>secretagent</rolename>
</authconstraint>
</securityconstraint>
<loginconfig>
<authmethod>BASIC</authmethod>
</loginconfig>

Each<securityconstraint>blockhasone<webresource
collection>sectionthatdesignatesanamedlistofURLpatternsforareasof
thewebapp,followedbyan<authconstraint>sectionlistinguserroles
thatareallowedtoaccessthoseareas.

https://www.safaribooksonline.com/library/view/learningjava4th/9781449372477/ch15s03.html

5/8

30/5/2015

WARFilesandDeploymentLearningJava,4thEdition

Wecandotheequivalentconfigurationforagivenservletusingthe
SecurityServletannotationwithanHttpConstraintannotationelementas
follows:

@ServletSecurity(
@HttpConstraint(rolesAllowed="secretagent")
)
publicclassSecureHelloClientextendsHttpServlet
{...

YoucanaddthisannotationtoourtestservletoraddtheXMLexamplesetup
totheweb.xmlfileforthelearningjava.warfileandpreparetotryitout.
However,thereisoneadditionalstepthatyoullhavetotaketogetthis
working:createtheuserrolesecretagentandanactualuserwiththisrolein
ourapplicationserverenvironment.
Accesstoprotectedareasisgrantedtouserroles,notindividualusers.Auser
roleiseffectivelyjustagroupofusersinsteadofgrantingaccesstoindividual
usersbyname,yougrantaccesstoroles,andusersareassignedoneormore
roles.Auserroleisanabstractionfromusers.Actualuserinformation(name
andpassword,etc.)ishandledoutsidethescopeofthewebapp,inthe
applicationserverenvironment(possiblyintegratedwiththehostplatform
operatingsystem).Generally,applicationservershavetheirowntoolsfor
creatingusersandassigningindividuals(oractualgroupsofusers)theirroles.
Agivenusernamemayhavemanyrolesassociatedwithit.
Whenattemptingtoaccessaloginprotectedarea,theusersvalidloginwillbe
assessedtoseeifshehasthecorrectroleforaccess.FortheTomcatserver,
addingtestusersandassigningthemrolesiseasysimplyeditthefile
conf/tomcatusers.xml.Toaddausernamedbondwiththesecretagentrole,
youdaddanentrysuchas:

<userusername="bond"password="007"roles="secretagent"/>

Forotherservers,youllhavetorefertothedocumentationtodeterminehowto
addusersandassignsecurityroles.

Secure Data Transport


Beforewemoveon,thereisonemorepieceofthesecurityconstraintto
discuss:thetransportguarantee.Each<securityconstraint>blockmay
endwitha<userdataconstraint>entry,whichdesignatesoneofthree
levelsoftransportsecurityfortheprotocolusedtotransferdatatoandfromthe
protectedareaovertheInternet.Forexample:
<securityconstraint>
...
<userdataconstraint>
<transportguarantee>CONFIDENTIAL</transportguarantee>
</userdataconstraint>
</securityconstraint>

ThethreelevelsareNONE,INTEGRAL,andCONFIDENTIAL.NONEis
equivalenttoleavingoutthesection,whichindicatesthatnospecialtransport
isrequired.Thisisthestandardfornormalwebtraffic,whichisgenerallysent
inplaintextoverthenetwork.TheINTEGRALlevelofsecurityspecifiesthat
anytransportprotocolusedmustguaranteethedatasentisnotmodifiedin
transit.Thisimpliestheuseofdigitalsignaturesorsomeothermethodof
validatingthedataatthereceivingend,butitdoesnotrequirethatthedatabe
encryptedandhiddenwhileitistransported.Finally,CONFIDENTIAL
impliesbothINTEGRALandencrypted.Inpractice,theonlywidelyused
securetransportinwebbrowsersisSSL.Requiringatransportguaranteeother
thanNONEtypicallyforcestheuseofSSLbytheclientbrowser.
Wecanconfiguretheequivalenttransportsecurityforaservletusingthe
ServletSecurityannotationalongwiththeHttpMethodConstraint
annotation,asfollows:

@ServletSecurity(
httpMethodConstraints=@HttpMethodConstraint(value="GET",
transportGuarantee=ServletSecurity.TransportGuarantee.CONFIDENTIAL
)
publicclassSecureHelloClientextendsHttpServlet{...}
@ServletSecurity(
value=@HttpConstraint(rolesAllowed="secretagent"),
httpMethodConstraints=@HttpMethodConstraint(value="GET",
transportGuarantee=ServletSecurity.TransportGuarantee.CONFIDENTIAL
)
publicclassSecureHelloClientextendsHttpServlet{...}

HereweusethehttpMethodConstraintsattributewithan
HttpMethodConstraintannotationtodesignatethattheservletmayonlybe
accessedusingtheHTTPGETmethodandonlywithCONFIDENTIALlevel
security.CombiningthetransportsecuritywitharolesAllowedannotation
canbedoneasshownintheprecedingexample.

Authenticating Users
Thissectionshowshowtodeclareacustomloginformtoperformuserlogin.

https://www.safaribooksonline.com/library/view/learningjava4th/9781449372477/ch15s03.html

6/8

30/5/2015

WARFilesandDeploymentLearningJava,4thEdition

First,wellshowtheweb.xmlstyleandthendiscusstheServlet3.0alternative,
whichgivesusmoreflexibility.
The<loginconf>sectiondeterminesexactlyhowauserauthenticates
herself(logsin)totheprotectedarea.The<authmethod>tagallowsfour
typesofloginauthenticationtobespecified:BASIC,DIGEST,FORM,and
CLIENTCERT.Inourexample,weshowedtheBASICmethod,whichusesthe
standardwebbrowserloginandpassworddialog.BASICauthenticationsends
theusersnameandpasswordinplaintextovertheInternetunlessatransport
guaranteehasbeenusedseparatelytostartSSLandencryptthedatastream.
DIGESTisavariationonBASICthatobscuresthetextofthepasswordbut
addslittlerealsecurityitisnotwidelyused.FORMisequivalenttoBASIC,
butinsteadofusingthebrowsersdialog,wecanuseourownHTMLformto
posttheusernameandpassworddatatothecontainer.Theformdatacancome
fromastaticHTMLpageorfromonegeneratedbyaservlet.Again,formdatais
sentinplaintextunlessotherwiseprotectedbyatransportguarantee(SSL).
CLIENTCERTisaninterestingoption.Itspecifiesthattheclientmustbe
identifiedusingaclientsidepublickeycertificate.Thisimpliestheuseofa
protocollikeSSL,whichallowsforsecureexchangeandmutualauthentication
usingdigitalcertificates.Theexactmethodofsettingupaclientside
certificateisbrowserdependent.
TheFORMmethodismostusefulbecauseitallowsustocustomizethelookof
theloginpage(werecommendusingSSLtosecurethedatastream).Wecan
alsospecifyanerrorpagetouseiftheauthenticationfails.Hereisasample
<loginconfig>usingtheformmethod:

<loginconfig>
<authmethod>FORM</authmethod>
<formloginconfig>
<formloginpage>/login.html</formloginpage>
<formerrorpage>/login_error.html</formerrorpage>
</formloginconfig>
</loginconfig>

TheloginpagemustcontainanHTMLformwithaspeciallynamedpairof
fieldsforthenameandpassword.Hereisasimplelogin.htmlfile:

<html>
<head><title>Login</title></head>
<body>
<formmethod="POST"action="j_security_check">
Username:<inputtype="text"name="j_username"><br>
Password:<inputtype="password"name="j_password"><br>
<inputtype="submit"value="submit">
</form>
</body>
</html>

Theusernamefieldiscalledj_username,thepasswordfieldiscalled
j_password,andtheURLusedfortheformactionattributeis
j_security_check.Therearenospecialrequirementsfortheerrorpage,but
normallyyouwillwanttoprovideatryagainmessageandrepeatthelogin
form.
IntheServlet3.0API,theHttpServletRequestAPIcontainsmethodsfor
explicitlylogginginandloggingoutauser.However,itisalsospecifiedthata
usersloginisnolongervalidaftertheusersessiontimesoutorisinvalidated.
Therefore,youcaneffectivelylogouttheuserbycallinginvalidate()on
thesession:

request.logout();request.getSession().invalidate();

WithServlet3.0,wecanalsotakecontroloftheloginprocessourselvesby
utilizingtheServletRequestlogin()methodtoperformourownlogin
operation.Allwehavetodoisarrangeourownloginservletthatacceptsa
usernameandpassword(securely)andthencallstheloginmethod.Thisgives
yougreatflexibilityoverhowandwhentheuserloginoccurs.And,ofcourse,
youcanlogtheuseroutwiththecorrespondinglogout()method.

@ServletSecurity(
httpMethodConstraints=@HttpMethodConstraint(value="POST",
transportGuarantee=ServletSecurity.TransportGuarantee.CONFIDENTIAL
)
@WebServlet(urlPatterns={"/mylogin"})
publicclassMyLoginextendsHttpServlet
{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse
throwsServletException,IOException
{
Stringuser=request.getParameter("user");
Stringpassword=request.getParameter("pass");
request.login(user,password);
//Dispatchorredirecttothenextpage...
}

Procedural Authorization
Weshouldmentionthatinadditiontothedeclarativesecurityofferedbythe
web.xmlfile,servletsmayperformtheirownactiveprocedural(or
programmatic)securityusingalltheauthenticationinformationavailableto

https://www.safaribooksonline.com/library/view/learningjava4th/9781449372477/ch15s03.html

7/8

30/5/2015

WARFilesandDeploymentLearningJava,4thEdition

thecontainer.Wewontcoverthisindetail,butherearethebasics.
Thenameoftheauthenticateduserisavailablethroughthemethod
HttpServletRequestgetRemoteUser(),andthetypeofauthentication
providedcanbedeterminedwiththegetAuthType()method.Servletscan
workwithsecurityrolesusingtheisUserInRole()method.(Doingthis
requiresaddingsomeadditionalmappingsintheweb.xmlfile,whichallows
theservlettorefertothesecurityrolesbyreferencenames.)
Foradvancedapplications,ajava.security.Principalobjectfortheuser
canberetrievedwiththegetUserPrincipal()methodoftherequest.Inthe
casewhereasecuretransportlikeSSLwasused,themethodisSecure()
returnstrue,anddetailedinformationabouthowtheprincipalwas
authenticatedtheciphertype,keysize,andcertificatechainismade
availablethroughrequestattributes.Itisusefultonotethatthenotionofbeing
loggedintoawebapplication,fromtheservletcontainerspointofview,is
definedastherebeingavalid(nonnull)valuereturnedbythe
getUserPrincipal()method.

PREV

Java Web Applicat

NEXT

Servlet Filters

Blog(http://blog.safaribooksonline.com) / Feedback(http://community.safaribooksonline.com/) / Sign In


2015 Safari(http://www.safaribooksonline.com/).
Terms of Service / Membership Agreement / Privacy Policy

https://www.safaribooksonline.com/library/view/learningjava4th/9781449372477/ch15s03.html

8/8

Das könnte Ihnen auch gefallen