Netscapeinternal

500InternalServerError  时间:2021-03-06  阅读:()
OracleCorporationwww.
oracle.
comSubmitcommentsaboutthisdocumentto:users@servlet-spec.
java.
netJavaServletSpecificationVersion3.
1RajivMordaniShingWaiChanJanuary2013PleaseRecycleSpecification:JSR-340JavaServlet3.
1Specification("Specification")Version:3.
1Status:PublicReviewRelease:09January2013Copyright2012OracleAmerica,Inc.
500OracleParkway,RedwoodCity,California94065,U.
S.
AAllrightsreserved.
LIMITEDLICENSEGRANTSNOTICETheSpecificationisprotectedbycopyrightandtheinformationdescribedthereinmaybeprotectedbyoneormoreU.
S.
patents,foreignpat-ents,orpendingapplications.
Exceptasprovidedunderthefollowinglicense,nopartoftheSpecificationmaybereproducedinanyformbyanymeanswithoutthepriorwrittenauthorizationofOracleAmerica,Inc.
("Oracle")anditslicensors,ifany.
AnyuseoftheSpecificationandtheinformationdescribedthereinwillbegovernedbythetermsandconditionsofthisAgreement.
Subjecttothetermsandconditionsofthislicense,includingyourcompliancewithParagraphs1and2below,Oracleherebygrantsyouafully-paid,non-exclusive,non-transferable,limitedlicense(withouttherighttosublicense)underOracle'sintellectualpropertyrightsto:1.
ReviewtheSpecificationforthepurposesofevaluation.
Thisincludes:(i)developingimplementationsoftheSpecificationforyourinternal,non-commercialuse;(ii)discussingtheSpecificationwithanythirdparty;and(iii)excerptingbriefportionsoftheSpecificationinoralorwrittencommunicationswhichdiscusstheSpecificationprovidedthatsuchexcerptsdonotintheaggregateconstituteasignificantportionoftheTechnology.
2.
DistributeimplementationsoftheSpecificationtothirdpartiesfortheirtestingandevaluationuse,providedthatanysuchimplementation:(i)doesnotmodify,subset,supersetorotherwiseextendtheLicensorNameSpace,orincludeanypublicorprotectedpackages,classes,Javainterfaces,fieldsormethodswithintheLicensorNameSpaceotherthanthoserequired/authorizedbytheSpecificationorSpecificationsbeingimplemented;(ii)isclearlyandprominentlymarkedwiththeword"UNTESTED"or"EARLYACCESS"or"INCOMPATIBLE"or"UNSTABLE"or"BETA"inanylistofavailablebuildsandinproximitytoeverylinkinitiatingitsdownload,wherethelistorlinkisunderLicensee'scontrol;and(iii)includesthefollowingnotice:"Thisisanimplementationofanearly-draftspecificationdevelopedundertheJavaCommunityProcess(JCP)andismadeavailablefortest-ingandevaluationpurposesonly.
ThecodeisnotcompatiblewithanyspecificationoftheJCP.
"Thegrantsetforthaboveconcerningyourdistributionofimplementationsofthespecificationiscontingentuponyouragreementtoterminatedevelopmentanddistributionofyour"earlydraft"implementationassoonasfeasiblefollowingfinalcompletionofthespecification.
Ifyoufailtodoso,theforegoinggrantshallbeconsiderednullandvoid.
NoprovisionofthisAgreementshallbeunderstoodtorestrictyourabilitytomakeanddistributetothirdpartiesapplicationswrittentotheSpecification.
Otherthanthislimitedlicense,youacquirenoright,titleorinterestinortotheSpecificationoranyotherOracleintellectualproperty,andtheSpecificationmayonlybeusedinaccordancewiththelicensetermssetforthherein.
Thislicensewillexpireontheearlierof:(a)two(2)yearsfromthedateofReleaselistedabove;(b)thedateonwhichthefinalversionoftheSpecificationispubliclyreleased;or(c)thedateonwhichtheJavaSpecificationRequest(JSR)towhichtheSpecificationcorrespondsiswithdrawn.
Inaddition,thislicensewillterminateimmediatelywithoutnoticefromOracleifyoufailtocomplywithanyprovisionofthislicense.
Upontermination,youmustceaseuseofordestroytheSpecification.
"LicensorNameSpace"meansthepublicclassorinterfacedeclarationswhosenamesbeginwith"java","javax","com.
oracle"ortheirequiv-alentsinanysubsequentnamingconventionadoptedbyOraclethroughtheJavaCommunityProcess,oranyrecognizedsuccessorsorreplacementsthereofTRADEMARKSNoright,title,orinterestinortoanytrademarks,servicemarks,ortradenamesofOracleorOracle'slicensorsisgrantedhereunder.
Oracle,theOraclelogo,JavaaretrademarksorregisteredtrademarksofOracleUSA,Inc.
intheU.
S.
andothercountries.
DISCLAIMEROFWARRANTIESTHESPECIFICATIONISPROVIDED"ASIS"ANDISEXPERIMENTALANDMAYCONTAINDEFECTSORDEFICIENCIESWHICHCANNOTORWILLNOTBECORRECTEDBYORACLE.
ORACLEMAKESNOREPRESENTATIONSORWARRANTIES,EITHEREXPRESSORIMPLIED,INCLUDINGBUTNOTLIMITEDTO,WARRANTIESOFMERCHANTABILITY,FITNESSFORAPARTICULARPURPOSE,ORNON-INFRINGEMENTTHATTHECONTENTSOFTHESPECIFICATIONARESUITABLEFORANYPURPOSEORTHATANYPRACTICEORIMPLEMENTATIONOFSUCHCONTENTSWILLNOTINFRINGEANYTHIRDPARTYPATENTS,COPYRIGHTS,TRADESECRETSOROTHERRIGHTS.
Thisdocumentdoesnotrepresentanycom-mitmenttoreleaseorimplementanyportionoftheSpecificationinanyproduct.
THESPECIFICATIONCOULDINCLUDETECHNICALINACCURACIESORTYPOGRAPHICALERRORS.
CHANGESAREPERI-ODICALLYADDEDTOTHEINFORMATIONTHEREIN;THESECHANGESWILLBEINCORPORATEDINTONEWVERSIONSOFTHESPECIFICATION,IFANY.
ORACLEMAYMAKEIMPROVEMENTSAND/ORCHANGESTOTHEPRODUCT(S)AND/ORTHEPROGRAM(S)DESCRIBEDINTHESPECIFICATIONATANYTIME.
AnyuseofsuchchangesintheSpecificationwillbegov-ernedbythethen-currentlicensefortheapplicableversionoftheSpecification.
LIMITATIONOFLIABILITYTOTHEEXTENTNOTPROHIBITEDBYLAW,INNOEVENTWILLORACLEORITSLICENSORSBELIABLEFORANYDAM-AGES,INCLUDINGWITHOUTLIMITATION,LOSTREVENUE,PROFITSORDATA,ORFORSPECIAL,INDIRECT,CONSE-QUENTIAL,INCIDENTALORPUNITIVEDAMAGES,HOWEVERCAUSEDANDREGARDLESSOFTHETHEORYOFLIABILITY,ARISINGOUTOFORRELATEDTOANYFURNISHING,PRACTICING,MODIFYINGORANYUSEOFTHESPECI-FICATION,EVENIFORACLEAND/ORITSLICENSORSHAVEBEENADVISEDOFTHEPOSSIBILITYOFSUCHDAMAGES.
YouwillholdOracle(anditslicensors)harmlessfromanyclaimsbasedonyouruseoftheSpecificationforanypurposesotherthanthelim-itedrightofevaluationasdescribedabove,andfromanyclaimsthatlaterversionsorreleasesofanySpecificationfurnishedtoyouareincom-patiblewiththeSpecificationprovidedtoyouunderthislicense.
RESTRICTEDRIGHTSLEGENDIfthisSoftwareisbeingacquiredbyoronbehalfoftheU.
S.
GovernmentorbyaU.
S.
Governmentprimecontractororsubcontractor(atanytier),thentheGovernment'srightsintheSoftwareandaccompanyingdocumentationshallbeonlyassetforthinthislicense;thisisinaccor-dancewith48C.
F.
R.
227.
7201through227.
7202-4(forDepartmentofDefense(DoD)acquisitions)andwith48C.
F.
R.
2.
101and12.
212(fornon-DoDacquisitions).
REPORTYoumaywishtoreportanyambiguities,inconsistenciesorinaccuraciesyoumayfindinconnectionwithyourevaluationoftheSpecification("Feedback").
TotheextentthatyouprovideOraclewithanyFeedback,youhereby:(i)agreethatsuchFeedbackisprovidedonanon-propri-etaryandnon-confidentialbasis,and(ii)grantOracleaperpetual,non-exclusive,worldwide,fullypaid-up,irrevocablelicense,withtherighttosublicensethroughmultiplelevelsofsublicensees,toincorporate,disclose,andusewithoutlimitationtheFeedbackforanypurposerelatedtotheSpecificationandfutureversions,implementations,andtestsuitesthereof.
GENERALTERMSAnyactionrelatedtothisAgreementwillbegovernedbyCalifornialawandcontrollingU.
S.
federallaw.
TheU.
N.
ConventionfortheInter-nationalSaleofGoodsandthechoiceoflawrulesofanyjurisdictionwillnotapply.
TheSpecificationissubjecttoU.
S.
exportcontrollawsandmaybesubjecttoexportorimportregulationsinothercountries.
Licenseeagreestocomplystrictlywithallsuchlawsandregulationsandacknowledgesthatithastheresponsibilitytoobtainsuchlicensestoexport,re-exportorimportasmayberequiredafterdeliverytoLicensee.
ThisAgreementistheparties'entireagreementrelatingtoitssubjectmatter.
Itsupersedesallpriororcontemporaneousoralorwrittencom-munications,proposals,conditions,representationsandwarrantiesandprevailsoveranyconflictingoradditionaltermsofanyquote,order,acknowledgment,orothercommunicationbetweenthepartiesrelatingtoitssubjectmatterduringthetermofthisAgreement.
Nomodifica-tiontothisAgreementwillbebinding,unlessinwritingandsignedbyanauthorizedrepresentativeofeachparty.
vPrefaceThisdocumentistheJavaServletSpecification,version3.
1.
ThestandardfortheJavaServletAPIisdescribedherein.
AdditionalSourcesThespecificationisintendedtobeacompleteandclearexplanationofJavaServlets,butifquestionsremain,thefollowingsourcesmaybeconsulted:Areferenceimplementation(RI)hasbeenmadeavailablewhichprovidesabehavioralbenchmarkforthisspecification.
Wherethespecificationleavesimplementationofaparticularfeatureopentointerpretation,implementorsmayusethereferenceimplementationasamodelofhowtocarryouttheintentionofthespecification.
Acompatibilitytestsuite(CTS)hasbeenprovidedforassessingwhetherimplementationsmeetthecompatibilityrequirementsoftheJavaServletAPIstandard.
Thetestresultshavenormativevalueforresolvingquestionsaboutwhetheranimplementationisstandard.
Iffurtherclarificationisrequired,theworkinggroupfortheJavaServletAPIundertheJavaCommunityProcessshouldbeconsulted,andisthefinalarbiterofsuchissues.
Commentsandfeedbackarewelcome,andwillbeusedtoimprovefutureversions.
WhoShouldReadThisSpecificationTheintendedaudienceforthisspecificationincludesthefollowinggroups:viJavaServletSpecificationNovember2009Webserverandapplicationservervendorsthatwanttoprovideservletenginesthatconformtothisstandard.
AuthoringtooldevelopersthatwanttosupportWebapplicationsthatconformtothisspecificationExperiencedservletauthorswhowanttounderstandtheunderlyingmechanismsofservlettechnology.
Weemphasizethatthisspecificationisnotauser'sguideforservletdevelopersandisnotintendedtobeusedassuch.
Referencesusefulforthispurposeareavailablefromhttp://java.
sun.
com/products/servlet.
APIReferenceThefullspecificationsofclasses,interfaces,andmethodsignaturesthatdefinetheJavaServletAPI,aswellastheiraccompanyingJavadocdocumentation,isavailableonline.
OtherJavaPlatformSpecificationsThefollowingJavaAPIspecificationsarereferencedthroughoutthisspecification:JavaPlatform,EnterpriseEdition("JavaEE"),version7JavaServerPages("JSP"),version2.
2JavaNamingandDirectoryInterface("J.
N.
D.
I.
").
ContextandDependencyInjectionfortheJavaEEPlatformManagedBeansspecificationThesespecificationsmaybefoundattheJavaPlatform,EnterpriseEditionWebsite:http://java.
sun.
com/javaee/.
OtherImportantReferencesThefollowingInternetspecificationsprovideinformationrelevanttothedevelopmentandimplementationoftheJavaServletAPIandstandardservletengines:PrefaceviiRFC1630UniformResourceIdentifiers(URI)RFC1738UniformResourceLocators(URL)RFC2396UniformResourceIdentifiers(URI):GenericSyntaxRFC1808RelativeUniformResourceLocatorsRFC1945HypertextTransferProtocol(HTTP/1.
0)RFC2045MIMEPartOne:FormatofInternetMessageBodiesRFC2046MIMEPartTwo:MediaTypesRFC2047MIMEPartThree:MessageHeaderExtensionsfornon-ASCIItextRFC2048MIMEPartFour:RegistrationProceduresRFC2049MIMEPartFive:ConformanceCriteriaandExamplesRFC2109HTTPStateManagementMechanismRFC2145UseandInterpretationofHTTPVersionNumbersRFC2324HypertextCoffeePotControlProtocol(HTCPCP/1.
0)1RFC2616HypertextTransferProtocol(HTTP/1.
1)RFC2617HTTPAuthentication:BasicandDigestAuthenticationRFC3986UniformResourceIdentifier(URI):GenericSyntaxOnlineversionsoftheseRFCsareathttp://wwww.
ietf.
org/rfc/.
TheWorldWideWebConsortium(http://www.
w3.
org/)isadefinitivesourceofHTTPrelatedinformationaffectingthisspecificationanditsimplementations.
TheeXtensibleMarkupLanguage(XML)isusedforthespecificationoftheDeploymentDescriptorsdescribedinChapter13ofthisspecification.
MoreinformationaboutXMLcanbefoundatthefollowingWebsites:http://java.
sun.
com/xmlhttp://www.
xml.
org/ProvidingFeedbackWewelcomeanyandallfeedbackaboutthisspecification.
Pleasee-mailyourcommentstousers@servlet-spec.
java.
net.
Pleasenotethatduetothevolumeoffeedbackthatwereceive,youwillnotnormallyreceiveareplyfromanengineer.
However,eachandeverycommentisread,evaluated,andarchivedbythespecificationteam.
1.
Thisreferenceismostlytongue-in-cheekalthoughmostoftheconceptsdescribedintheHTCPCPRFCarerelevanttoallwell-designedWebservers.
viiiJavaServletSpecificationNovember2009ExpertGroupmembersDeepakAnupalli(PramatiTechnologies)EuigeunChung(TmaxSoft,Inc)RobertGoff(IBM)RichardHightowerSethHodgson(AdobeSystemsInc.
)RemyMaucherat(RedHat)MinoruNitta(FujitsuLimited)RameshPVK(PramatiTechnnologies)AlexRojkov(CauchoTechnologies)MarkThomas(VMware)GregoryJohnWilkinsWenboZhu(GoogleInc.
)AcknowledgementsBillShannonfromOraclehasprovidedinvaluabletechnicalinputtothespecification.
RonMonzillofromOraclehashelpeddrivesomeoftheproposalsandtechnicaldiscussionsaroundsecurityaspects.
ixContentsContentsix1.
Overview11.
1WhatisaServlet11.
2WhatisaServletContainer11.
3AnExample21.
4ComparingServletswithOtherTechnologies31.
5RelationshiptoJavaPlatform,EnterpriseEdition31.
6CompatibilitywithJavaServletSpecificationVersion2.
541.
6.
1Processingannotations42.
TheServletInterface52.
1RequestHandlingMethods52.
1.
1HTTPSpecificRequestHandlingMethods52.
1.
2AdditionalMethods62.
1.
3ConditionalGETSupport62.
2NumberofInstances62.
2.
1NoteAboutTheSingleThreadModel72.
3ServletLifeCycle72.
3.
1LoadingandInstantiation7xJavaServletSpecification2.
3.
2Initialization82.
3.
2.
1ErrorConditionsonInitialization82.
3.
2.
2ToolConsiderations82.
3.
3RequestHandling92.
3.
3.
1MultithreadingIssues92.
3.
3.
2ExceptionsDuringRequestHandling92.
3.
3.
3Asynchronousprocessing102.
3.
3.
4ThreadSafety202.
3.
3.
5UpgradeProcessing202.
3.
4EndofService213.
TheRequest233.
1HTTPProtocolParameters233.
1.
1WhenParametersAreAvailable243.
2Fileupload243.
3Attributes253.
4Headers253.
5RequestPathElements263.
6PathTranslationMethods273.
7NonBlockingIO283.
8Cookies293.
9SSLAttributes303.
10Internationalization303.
11Requestdataencoding313.
12LifetimeoftheRequestObject314.
ServletContext334.
1IntroductiontotheServletContextInterface334.
2ScopeofaServletContextInterface33Contentsxi4.
3InitializationParameters344.
4Configurationmethods344.
4.
1ProgrammaticallyaddingandconfiguringServlets354.
4.
1.
1addServlet(StringservletName,StringclassName)354.
4.
1.
2addServlet(StringservletName,Servletservlet)354.
4.
1.
3addServlet(StringservletName,ClassservletClass)354.
4.
1.
4TcreateServlet(Classclazz)354.
4.
1.
5ServletRegistrationgetServletRegistration(StringservletName)364.
4.
1.
6MapgetServletRegistrations()364.
4.
2ProgrammaticallyaddingandconfiguringFilters364.
4.
2.
1addFilter(StringfilterName,StringclassName)364.
4.
2.
2addFilter(StringfilterName,Filterfilter)364.
4.
2.
3addFilter(StringfilterName,ClassfilterClass)374.
4.
2.
4TcreateFilter(Classclazz)374.
4.
2.
5FilterRegistrationgetFilterRegistration(StringfilterName)374.
4.
2.
6MapgetServletRegistrations()374.
4.
3ProgrammaticallyaddingandconfiguringListeners384.
4.
3.
1voidaddListener(StringclassName)384.
4.
3.
2voidaddListener(Tt)384.
4.
3.
3voidaddListener(ClasslistenerClass)394.
4.
3.
4voidcreateListener(Classclazz)394.
4.
3.
5AnnotationprocessingrequirementsforprogrammaticallyaddedServlets,FiltersandListeners40xiiJavaServletSpecification4.
5ContextAttributes404.
5.
1ContextAttributesinaDistributedContainer414.
6Resources414.
7MultipleHostsandServletContexts424.
8ReloadingConsiderations424.
8.
1TemporaryWorkingDirectories425.
TheResponse455.
1Buffering455.
2Headers465.
3NonBlockingIO475.
4ConvenienceMethods485.
5Internationalization495.
6ClosureofResponseObject505.
7LifetimeoftheResponseObject506.
Filtering516.
1Whatisafilter516.
1.
1ExamplesofFilteringComponents526.
2MainConcepts526.
2.
1FilterLifecycle526.
2.
2WrappingRequestsandResponses546.
2.
3FilterEnvironment546.
2.
4ConfigurationofFiltersinaWebApplication556.
2.
5FiltersandtheRequestDispatcher587.
Sessions617.
1SessionTrackingMechanisms617.
1.
1Cookies617.
1.
2SSLSessions62Contentsxiii7.
1.
3URLRewriting627.
1.
4SessionIntegrity627.
2CreatingaSession627.
3SessionScope637.
4BindingAttributesintoaSession647.
5SessionTimeouts647.
6LastAccessedTimes657.
7ImportantSessionSemantics657.
7.
1ThreadingIssues657.
7.
2DistributedEnvironments657.
7.
3ClientSemantics668.
Annotationsandpluggability678.
1Annotationsandpluggability678.
1.
1@WebServlet678.
1.
2@WebFilter698.
1.
3@WebInitParam698.
1.
4@WebListener698.
1.
5@MultipartConfig708.
1.
6Otherannotations/conventions708.
2Pluggability718.
2.
1Modularityofweb.
xml718.
2.
2Orderingofweb.
xmlandweb-fragment.
xml738.
2.
3Assemblingthedescriptorfromweb.
xml,web-fragment.
xmlandannotations788.
2.
4Sharedlibraries/runtimespluggability918.
3JSPcontainerpluggability938.
4Processingannotationsandfragments949.
DispatchingRequests95xivJavaServletSpecification9.
1ObtainingaRequestDispatcher959.
1.
1QueryStringsinRequestDispatcherPaths969.
2UsingaRequestDispatcher969.
3TheIncludeMethod979.
3.
1IncludedRequestParameters979.
4TheForwardMethod989.
4.
1QueryString989.
4.
2ForwardedRequestParameters989.
5ErrorHandling999.
6ObtaininganAsyncContext999.
7TheDispatchMethod1009.
7.
1QueryString1009.
7.
2DispatchedRequestParameters10010.
WebApplications10310.
1WebApplicationsWithinWebServers10310.
2RelationshiptoServletContext10310.
3ElementsofaWebApplication10410.
4DeploymentHierarchies10410.
5DirectoryStructure10410.
5.
1ExampleofApplicationDirectoryStructure10610.
6WebApplicationArchiveFile10610.
7WebApplicationDeploymentDescriptor10610.
7.
1DependenciesOnExtensions10710.
7.
2WebApplicationClassLoader10710.
8ReplacingaWebApplication10810.
9ErrorHandling10810.
9.
1RequestAttributes10810.
9.
2ErrorPages109Contentsxv10.
9.
3ErrorFilters11110.
10WelcomeFiles11110.
11WebApplicationEnvironment11210.
12WebApplicationDeployment11310.
13Inclusionofaweb.
xmlDeploymentDescriptor11311.
ApplicationLifecycleEvents11511.
1Introduction11511.
2EventListeners11511.
2.
1EventTypesandListenerInterfaces11611.
2.
2AnExampleofListenerUse11711.
3ListenerClassConfiguration11711.
3.
1ProvisionofListenerClasses11711.
3.
2DeploymentDeclarations11811.
3.
3ListenerRegistration11811.
3.
4NotificationsAtShutdown11811.
4DeploymentDescriptorExample11811.
5ListenerInstancesandThreading11911.
6ListenerExceptions11911.
7DistributedContainers12011.
8SessionEvents12012.
MappingRequeststoServlets12112.
1UseofURLPaths12112.
2SpecificationofMappings12212.
2.
1ImplicitMappings12212.
2.
2ExampleMappingSet12313.
Security12513.
1Introduction125xviJavaServletSpecification13.
2DeclarativeSecurity12613.
3ProgrammaticSecurity12613.
4ProgrammaticSecurityPolicyConfiguration12813.
4.
1@ServletSecurityAnnotation12813.
4.
1.
1Examples13213.
4.
1.
2Mapping@ServletSecuritytosecurity-constraint13313.
4.
1.
3Mapping@HttpConstraintand@HttpMethodConstrainttoXML.
13513.
4.
2setServletSecurityofServletRegistration.
Dynamic13613.
5Roles13713.
6Authentication13813.
6.
1HTTPBasicAuthentication13813.
6.
2HTTPDigestAuthentication13813.
6.
3FormBasedAuthentication13913.
6.
3.
1LoginFormNotes14013.
6.
4HTTPSClientAuthentication14113.
6.
5AdditionalContainerAuthenticationMechanisms14113.
7ServerTrackingofAuthenticationInformation14113.
8SpecifyingSecurityConstraints14213.
8.
1CombiningConstraints14313.
8.
2Example14413.
8.
3ProcessingRequests14613.
8.
4UncoveredHTTPProtocolMethods14713.
8.
4.
1RulesforSecurityConstraintConfiguration14913.
8.
4.
2HandlingUncoveredHTTPMethods14913.
9DefaultPolicies15013.
10LoginandLogout15114.
DeploymentDescriptor153Contentsxvii14.
1DeploymentDescriptorElements15314.
2RulesforProcessingtheDeploymentDescriptor15414.
3DeploymentDescriptor15514.
4DeploymentDescriptorDiagram15514.
5Examples17814.
5.
1ABasicExample17914.
5.
2AnExampleofSecurity18015.
RequirementsrelatedtootherSpecifications18315.
1Sessions18315.
2WebApplications18315.
2.
1WebApplicationClassLoader18315.
2.
2WebApplicationEnvironment18415.
2.
3JNDINameforWebModuleContextRootURL18415.
3Security18515.
3.
1PropagationofSecurityIdentityinEJBCalls18615.
3.
2ContainerAuthorizationRequirements18615.
3.
3ContainerAuthenticationRequirements18615.
4Deployment18715.
4.
1DeploymentDescriptorElements18715.
4.
2PackagingandDeploymentofJAX-WSComponents18715.
4.
3RulesforProcessingtheDeploymentDescriptor18915.
5AnnotationsandResourceInjection18915.
5.
1@DeclareRoles19015.
5.
2@EJBAnnotation19115.
5.
3@EJBsAnnotation19215.
5.
4@ResourceAnnotation19215.
5.
5@PersistenceContextAnnotation19315.
5.
6@PersistenceContextsAnnotation193xviiiJavaServletSpecification15.
5.
7@PersistenceUnitAnnotation19415.
5.
8@PersistenceUnitsAnnotation19415.
5.
9@PostConstructAnnotation19415.
5.
10@PreDestroyAnnotation19515.
5.
11@ResourcesAnnotation19515.
5.
12@RunAsAnnotation19615.
5.
13@WebServiceRefAnnotation19715.
5.
14@WebServiceRefsAnnotation19715.
5.
15ContextsandDependencyInjectionforJavaEErequirements197A.
ChangeLog199A.
1ChangessinceServlet3.
0199A.
2ChangessinceServlet3.
0ProposedFinalDraft201A.
3ChangessinceServlet3.
0PublicReview202A.
4ChangessinceServlet3.
0EDR202A.
5ChangessinceServlet2.
5MR6202A.
6ChangessinceServlet2.
5MR5203A.
6.
1ClarifySRV8.
4"TheForwardMethod"203A.
6.
2UpdateDeploymentdescriptor"http-methodvaluesallowed"203A.
6.
3ClarifySRV7.
7.
1"ThreadingIssues"204A.
7ChangesSinceServlet2.
5MR2204A.
7.
1UpdatedAnnotationRequirementsforJavaEEcontainers204A.
7.
2UpdatedJavaEnterpriseEditionRequirements204A.
7.
3ClarifiedHttpServletRequest.
getRequestURL()204A.
7.
4RemovalofIllegalStateExceptionfromHttpSession.
getId()205A.
7.
5ServletContext.
getContextPath()205A.
7.
6Requirementforweb.
xmlinwebapplications206A.
8ChangesSinceServlet2.
4206ContentsxixA.
8.
1SessionClarification206A.
8.
2FilterAllDispatches207A.
8.
3MultipleOccurrencesofServletMappings207A.
8.
4MultipleOccurrencesFilterMappings208A.
8.
5SupportAlternativeHTTPMethodswithAuthorizationConstraints209A.
8.
6MinimumJ2SERequirement210A.
8.
7AnnotationsandResourceInjection210A.
8.
8SRV.
9.
9("ErrorHandling")RequirementRemoved210A.
8.
9HttpServletRequest.
isRequestedSessionIdValid()Clarification210A.
8.
10SRV.
5.
5("ClosureofResponseObject")Clarification210A.
8.
11ServletRequest.
setCharacterEncoding()Clarified211A.
8.
12JavaEnterpriseEditionRequirements211A.
8.
13Servlet2.
4MRChangeLogUpdatesAdded211A.
8.
14SynchronizedAccessSessionObjectClarified211A.
9ChangesSinceServlet2.
3211xxJavaServletSpecification1CHAPTER1Overview1.
1WhatisaServletAservletisaJavatechnology-basedWebcomponent,managedbyacontainer,thatgeneratesdynamiccontent.
LikeotherJavatechnology-basedcomponents,servletsareplatform-independentJavaclassesthatarecompiledtoplatform-neutralbytecodethatcanbeloadeddynamicallyintoandrunbyaJavatechnology-enabledWebserver.
Containers,sometimescalledservletengines,areWebserverextensionsthatprovideservletfunctionality.
ServletsinteractwithWebclientsviaarequest/responseparadigmimplementedbytheservletcontainer.
1.
2WhatisaServletContainerTheservletcontainerisapartofaWebserverorapplicationserverthatprovidesthenetworkservicesoverwhichrequestsandresponsesaresent,decodesMIME-basedrequests,andformatsMIME-basedresponses.
Aservletcontaineralsocontainsandmanagesservletsthroughtheirlifecycle.
AservletcontainercanbebuiltintoahostWebserver,orinstalledasanadd-oncomponenttoaWebServerviathatserver'snativeextensionAPI.
ServletcontainerscanalsobebuiltintoorpossiblyinstalledintoWeb-enabledapplicationservers.
AllservletcontainersmustsupportHTTPasaprotocolforrequestsandresponses,butadditionalrequest/response-basedprotocolssuchasHTTPS(HTTPoverSSL)maybesupported.
TherequiredversionsoftheHTTPspecificationthatacontainermustimplementareHTTP/1.
0andHTTP/1.
1.
BecausethecontainermayhaveacachingmechanismdescribedinRFC2616(HTTP/1.
1),itmaymodifyrequestsfrom2JavaServletSpecificationtheclientsbeforedeliveringthemtotheservlet,maymodifyresponsesproducedbyservletsbeforesendingthemtotheclients,ormayrespondtorequestswithoutdeliveringthemtotheservletunderthecompliancewithRFC2616.
Aservletcontainermayplacesecurityrestrictionsontheenvironmentinwhichaservletexecutes.
InaJavaPlatform,StandardEdition(J2SE,v.
1.
3orabove)orJavaPlatform,EnterpriseEdition(JavaEE,v.
1.
3orabove)environment,theserestrictionsshouldbeplacedusingthepermissionarchitecturedefinedbytheJavaplatform.
Forexample,high-endapplicationserversmaylimitthecreationofaThreadobjecttoinsurethatothercomponentsofthecontainerarenotnegativelyimpacted.
JavaSE7istheminimumversionoftheunderlyingJavaplatformwithwhichservletcontainersmustbebuilt.
1.
3AnExampleThefollowingisatypicalsequenceofevents:1.
Aclient(e.
g.
,aWebbrowser)accessesaWebserverandmakesanHTTPrequest.
2.
TherequestisreceivedbytheWebserverandhandedofftotheservletcontainer.
TheservletcontainercanberunninginthesameprocessasthehostWebserver,inadifferentprocessonthesamehost,oronadifferenthostfromtheWebserverforwhichitprocessesrequests.
3.
Theservletcontainerdetermineswhichservlettoinvokebasedontheconfigurationofitsservlets,andcallsitwithobjectsrepresentingtherequestandresponse.
4.
Theservletusestherequestobjecttofindoutwhotheremoteuseris,whatHTTPPOSTparametersmayhavebeensentaspartofthisrequest,andotherrelevantdata.
Theservletperformswhateverlogicitwasprogrammedwith,andgeneratesdatatosendbacktotheclient.
Itsendsthisdatabacktotheclientviatheresponseobject.
5.
Oncetheservlethasfinishedprocessingtherequest,theservletcontainerensuresthattheresponseisproperlyflushed,andreturnscontrolbacktothehostWebserver.
Chapter1Overview31.
4ComparingServletswithOtherTechnologiesInfunctionality,servletsliesomewherebetweenCommonGatewayInterface(CGI)programsandproprietaryserverextensionssuchastheNetscapeServerAPI(NSAPI)orApacheModules.
Servletshavethefollowingadvantagesoverotherserverextensionmechanisms:TheyaregenerallymuchfasterthanCGIscriptsbecauseadifferentprocessmodelisused.
TheyuseastandardAPIthatissupportedbymanyWebservers.
TheyhavealltheadvantagesoftheJavaprogramminglanguage,includingeaseofdevelopmentandplatformindependence.
TheycanaccessthelargesetofAPIsavailablefortheJavaplatform.
1.
5RelationshiptoJavaPlatform,EnterpriseEditionTheJavaServletAPIv.
3.
1isarequiredAPIoftheJavaPlatform,EnterpriseEdition,71.
Servletcontainersandservletsdeployedintothemmustmeetadditionalrequirements,describedintheJavaEEspecification,forexecutinginaJavaEEenvironment.
1.
PleaseseetheJavaPlatform,EnterpriseEditionspecificationavailableathttp://www.
oracle.
com/technetwork/java/javaee/tech/index.
html4JavaServletSpecification1.
6CompatibilitywithJavaServletSpecificationVersion2.
51.
6.
1ProcessingannotationsInServlet2.
5,metadata-completeonlyaffectedthescanningofannotationsatdeploymenttime.
Thenotionofweb-fragmentsdidnotexistinservlet2.
5.
Howeverinservlet3.
0andlater,metadata-completeaffectsscanningofallannotationsthatspecifydeploymentinformationandweb-fragmentsatdeploymenttime.
TheversionofthedescriptorMUSTnotaffectwhichannotationsyouscanforinawebapplication.
AnimplementationofaparticularversionofthespecificationMUSTscanforallannotationssupportedinthatconfiguration,unlessmetadata-completeisspecified.
5CHAPTER2TheServletInterfaceTheServletinterfaceisthecentralabstractionoftheJavaServletAPI.
Allservletsimplementthisinterfaceeitherdirectly,ormorecommonly,byextendingaclassthatimplementstheinterface.
ThetwoclassesintheJavaServletAPIthatimplementtheServletinterfaceareGenericServletandHttpServlet.
Formostpurposes,DeveloperswillextendHttpServlettoimplementtheirservlets.
2.
1RequestHandlingMethodsThebasicServletinterfacedefinesaservicemethodforhandlingclientrequests.
Thismethodiscalledforeachrequestthattheservletcontainerroutestoaninstanceofaservlet.
ThehandlingofconcurrentrequeststoaWebapplicationgenerallyrequiresthattheWebDeveloperdesignservletsthatcandealwithmultiplethreadsexecutingwithintheservicemethodataparticulartime.
GenerallytheWebcontainerhandlesconcurrentrequeststothesameservletbyconcurrentexecutionoftheservicemethodondifferentthreads.
2.
1.
1HTTPSpecificRequestHandlingMethodsTheHttpServletabstractsubclassaddsadditionalmethodsbeyondthebasicServletinterfacethatareautomaticallycalledbytheservicemethodintheHttpServletclasstoaidinprocessingHTTP-basedrequests.
Thesemethodsare:doGetforhandlingHTTPGETrequestsdoPostforhandlingHTTPPOSTrequestsdoPutforhandlingHTTPPUTrequestsdoDeleteforhandlingHTTPDELETErequests6JavaServletSpecificationdoHeadforhandlingHTTPHEADrequestsdoOptionsforhandlingHTTPOPTIONSrequestsdoTraceforhandlingHTTPTRACErequestsTypicallywhendevelopingHTTP-basedservlets,aServletDeveloperwillonlyconcernhimselfwiththedoGetanddoPostmethods.
TheothermethodsareconsideredtobemethodsforusebyprogrammersveryfamiliarwithHTTPprogramming.
2.
1.
2AdditionalMethodsThedoPutanddoDeletemethodsallowServletDeveloperstosupportHTTP/1.
1clientsthatemploythesefeatures.
ThedoHeadmethodinHttpServletisaspecializedformofthedoGetmethodthatreturnsonlytheheadersproducedbythedoGetmethod.
ThedoOptionsmethodrespondswithwhichHTTPmethodsaresupportedbytheservlet.
ThedoTracemethodgeneratesaresponsecontainingallinstancesoftheheaderssentintheTRACErequest.
2.
1.
3ConditionalGETSupportTheHttpServletinterfacedefinesthegetLastModifiedmethodtosupportconditionalGEToperations.
AconditionalGEToperationrequestsaresourcebesentonlyifithasbeenmodifiedsinceaspecifiedtime.
Inappropriatesituations,implementationofthismethodmayaidefficientutilizationofnetworkresources.
2.
2NumberofInstancesTheservletdeclarationwhichiseitherviatheannotationasdescribedinChapter8,"Annotationsandpluggability"orpartofthedeploymentdescriptoroftheWebapplicationcontainingtheservlet,asdescribedinChapter14,"DeploymentDescriptor",controlshowtheservletcontainerprovidesinstancesoftheservlet.
Foraservletnothostedinadistributedenvironment(thedefault),theservletcontainermustuseonlyoneinstanceperservletdeclaration.
However,foraservletimplementingtheSingleThreadModelinterface,theservletcontainermayinstantiatemultipleinstancestohandleaheavyrequestloadandserializerequeststoaparticularinstance.
Chapter2TheServletInterface7Inthecasewhereaservletwasdeployedaspartofanapplicationmarkedinthedeploymentdescriptorasdistributable,acontainermayhaveonlyoneinstanceperservletdeclarationperJavaVirtualMachine(JVM)1.
However,iftheservletinadistributableapplicationimplementstheSingleThreadModelinterface,thecontainermayinstantiatemultipleinstancesofthatservletineachJVMofthecontainer.
2.
2.
1NoteAboutTheSingleThreadModelTheuseoftheSingleThreadModelinterfaceguaranteesthatonlyonethreadatatimewillexecuteinagivenservletinstance'sservicemethod.
Itisimportanttonotethatthisguaranteeonlyappliestoeachservletinstance,sincethecontainermaychoosetopoolsuchobjects.
Objectsthatareaccessibletomorethanoneservletinstanceatatime,suchasinstancesofHttpSession,maybeavailableatanyparticulartimetomultipleservlets,includingthosethatimplementSingleThreadModel.
Itisrecommendedthatadevelopertakeothermeanstoresolvethoseissuesinsteadofimplementingthisinterface,suchasavoidingtheusageofaninstancevariableorsynchronizingtheblockofthecodeaccessingthoseresources.
TheSingleThreadModelInterfaceisdeprecatedinthisversionofthespecification.
2.
3ServletLifeCycleAservletismanagedthroughawelldefinedlifecyclethatdefineshowitisloadedandinstantiated,isinitialized,handlesrequestsfromclients,andistakenoutofservice.
ThislifecycleisexpressedintheAPIbytheinit,service,anddestroymethodsofthejavax.
servlet.
ServletinterfacethatallservletsmustimplementdirectlyorindirectlythroughtheGenericServletorHttpServletabstractclasses.
2.
3.
1LoadingandInstantiationTheservletcontainerisresponsibleforloadingandinstantiatingservlets.
Theloadingandinstantiationcanoccurwhenthecontainerisstarted,ordelayeduntilthecontainerdeterminestheservletisneededtoservicearequest.
1.
Theterms"Javavirtualmachine"and"JVM"meanavirtualmachinefortheJava()platform.
8JavaServletSpecificationWhentheservletengineisstarted,neededservletclassesmustbelocatedbytheservletcontainer.
TheservletcontainerloadstheservletclassusingnormalJavaclassloadingfacilities.
Theloadingmaybefromalocalfilesystem,aremotefilesystem,orothernetworkservices.
AfterloadingtheServletclass,thecontainerinstantiatesitforuse.
2.
3.
2InitializationAftertheservletobjectisinstantiated,thecontainermustinitializetheservletbeforeitcanhandlerequestsfromclients.
Initializationisprovidedsothataservletcanreadpersistentconfigurationdata,initializecostlyresources(suchasJDBCAPI-basedconnections),andperformotherone-timeactivities.
ThecontainerinitializestheservletinstancebycallingtheinitmethodoftheServletinterfacewithaunique(perservletdeclaration)objectimplementingtheServletConfiginterface.
Thisconfigurationobjectallowstheservlettoaccessname-valueinitializationparametersfromtheWebapplication'sconfigurationinformation.
Theconfigurationobjectalsogivestheservletaccesstoanobject(implementingtheServletContextinterface)thatdescribestheservlet'sruntimeenvironment.
SeeChapter4,"ServletContext"formoreinformationabouttheServletContextinterface.
2.
3.
2.
1ErrorConditionsonInitializationDuringinitialization,theservletinstancecanthrowanUnavailableExceptionoraServletException.
Inthiscase,theservletmustnotbeplacedintoactiveserviceandmustbereleasedbytheservletcontainer.
Thedestroymethodisnotcalledasitisconsideredunsuccessfulinitialization.
Anewinstancemaybeinstantiatedandinitializedbythecontainerafterafailedinitialization.
TheexceptiontothisruleiswhenanUnavailableExceptionindicatesaminimumtimeofunavailability,andthecontainermustwaitfortheperiodtopassbeforecreatingandinitializinganewservletinstance.
2.
3.
2.
2ToolConsiderationsThetriggeringofstaticinitializationmethodswhenatoolloadsandintrospectsaWebapplicationistobedistinguishedfromthecallingoftheinitmethod.
DevelopersshouldnotassumeaservletisinanactivecontainerruntimeuntiltheinitmethodoftheServletinterfaceiscalled.
Forexample,aservletshouldnottrytoestablishconnectionstodatabasesorEnterpriseJavaBeanscontainerswhenonlystatic(class)initializationmethodshavebeeninvoked.
Chapter2TheServletInterface92.
3.
3RequestHandlingAfteraservletisproperlyinitialized,theservletcontainermayuseittohandleclientrequests.
RequestsarerepresentedbyrequestobjectsoftypeServletRequest.
TheservletfillsoutresponsetorequestsbycallingmethodsofaprovidedobjectoftypeServletResponse.
TheseobjectsarepassedasparameterstotheservicemethodoftheServletinterface.
InthecaseofanHTTPrequest,theobjectsprovidedbythecontainerareoftypesHttpServletRequestandHttpServletResponse.
Notethataservletinstanceplacedintoservicebyaservletcontainermayhandlenorequestsduringitslifetime.
2.
3.
3.
1MultithreadingIssuesAservletcontainermaysendconcurrentrequeststhroughtheservicemethodoftheservlet.
Tohandletherequests,theServletDevelopermustmakeadequateprovisionsforconcurrentprocessingwithmultiplethreadsintheservicemethod.
Althoughitisnotrecommended,analternativefortheDeveloperistoimplementtheSingleThreadModelinterfacewhichrequiresthecontainertoguaranteethatthereisonlyonerequestthreadatatimeintheservicemethod.
Aservletcontainermaysatisfythisrequirementbyserializingrequestsonaservlet,orbymaintainingapoolofservletinstances.
IftheservletispartofaWebapplicationthathasbeenmarkedasdistributable,thecontainermaymaintainapoolofservletinstancesineachJVMthattheapplicationisdistributedacross.
ForservletsnotimplementingtheSingleThreadModelinterface,iftheservicemethod(ormethodssuchasdoGetordoPostwhicharedispatchedtotheservicemethodoftheHttpServletabstractclass)hasbeendefinedwiththesynchronizedkeyword,theservletcontainercannotusetheinstancepoolapproach,butmustserializerequeststhroughit.
ItisstronglyrecommendedthatDevelopersnotsynchronizetheservicemethod(ormethodsdispatchedtoit)inthesecircumstancesbecauseofdetrimentaleffectsonperformance.
2.
3.
3.
2ExceptionsDuringRequestHandlingAservletmaythroweitheraServletExceptionoranUnavailableExceptionduringtheserviceofarequest.
AServletExceptionsignalsthatsomeerroroccurredduringtheprocessingoftherequestandthatthecontainershouldtakeappropriatemeasurestocleanuptherequest.
AnUnavailableExceptionsignalsthattheservletisunabletohandlerequestseithertemporarilyorpermanently.
10JavaServletSpecificationIfapermanentunavailabilityisindicatedbytheUnavailableException,theservletcontainermustremovetheservletfromservice,callitsdestroymethod,andreleasetheservletinstance.
AnyrequestsrefusedbythecontainerbythatcausemustbereturnedwithaSC_NOT_FOUND(404)response.
IftemporaryunavailabilityisindicatedbytheUnavailableException,thecontainermaychoosetonotrouteanyrequeststhroughtheservletduringthetimeperiodofthetemporaryunavailability.
AnyrequestsrefusedbythecontainerduringthisperiodmustbereturnedwithaSC_SERVICE_UNAVAILABLE(503)responsestatusalongwithaRetry-Afterheaderindicatingwhentheunavailabilitywillterminate.
ThecontainermaychoosetoignorethedistinctionbetweenapermanentandtemporaryunavailabilityandtreatallUnavailableExceptionsaspermanent,therebyremovingaservletthatthrowsanyUnavailableExceptionfromservice.
2.
3.
3.
3AsynchronousprocessingSometimesafilterand/orservletisunabletocompletetheprocessingofarequestwithoutwaitingforaresourceoreventbeforegeneratingaresponse.
Forexample,aservletmayneedtowaitforanavailableJDBCconnection,foraresponsefromaremotewebservice,foraJMSmessage,orforanapplicationevent,beforeproceedingtogeneratearesponse.
Waitingwithintheservletisaninefficientoperationasitisablockingoperationthatconsumesathreadandotherlimitedresources.
Frequentlyaslowresourcesuchasadatabasemayhavemanythreadsblockedwaitingforaccessandcancausethreadstarvationandpoorqualityofserviceforanentirewebcontainer.
Servlet3.
0introducestheabilityforasynchronousprocessingofrequestssothatthethreadmayreturntothecontainerandperformothertasks.
Whenasynchronousprocessingbeginsontherequest,anotherthreadorcallbackmayeithergeneratetheresponseandcallcompleteordispatchtherequestsothatitmayruninthecontextofthecontainerusingtheAsyncContext.
dispatchmethod.
Atypicalsequenceofeventsforasynchronousprocessingis:1.
Therequestisreceivedandpassedvianormalfiltersforauthenticationetc.
totheservlet.
2.
Theservletprocessestherequestparametersand/orcontenttodeterminethenatureoftherequest.
3.
Theservletissuesrequestsforresourcesordata,forexample,sendsaremotewebservicerequestorjoinsaqueuewaitingforaJDBCconnection.
4.
Theservletreturnswithoutgeneratingaresponse.
5.
Aftersometime,therequestedresourcebecomesavailable,thethreadhandlingthateventcontinuesprocessingeitherinthesamethreadorbydispatchingtoaresourceinthecontainerusingtheAsyncContext.
Chapter2TheServletInterface11JavaEnterpriseEditionfeaturessuchasSection15.
2.
2,"WebApplicationEnvironment"onpage15-184andSection15.
3.
1,"PropagationofSecurityIdentityinEJBCalls"onpage15-186areavailableonlytothreadsexecutingtheinitialrequestorwhentherequestisdispatchedtothecontainerviatheAsyncContext.
dispatchmethod.
JavaEnterpriseEditionfeaturesmaybeavailabletootherthreadsoperatingdirectlyontheresponseobjectviatheAsyncContext.
start(Runnable)method.
The@WebServletand@WebFilterannotationsdescribedinChapter8haveanattribute-asyncSupportedthatisabooleanwithadefaultvalueoffalse.
WhenasyncSupportedissettotruetheapplicationcanstartasynchronousprocessinginaseparatethreadbycallingstartAsync(seebelow),passingitareferencetotherequestandresponseobjects,andthenexitfromthecontainerontheoriginalthread.
Thismeansthattheresponsewilltraverse(inreverseorder)thesamefilters(orfilterchain)thatweretraversedonthewayin.
Theresponseisn'tcommittedtillcomplete(seebelow)iscalledontheAsyncContext.
Theapplicationisresponsibletohandleconcurrentaccesstotherequestandresponseobjectsiftheasynctaskisexecutingbeforethecontainer-initiateddispatchthatcalledstartAsynchasreturnedtothecontainer.
DispatchingfromaservletthathasasyncSupported=truetoonewhereasyncSupportedissettofalseisallowed.
Inthiscase,theresponsewillbecommittedwhentheservicemethodoftheservletthatdoesnotsupportasyncisexited,anditisthecontainer'sresponsibilitytocallcompleteontheAsyncContextsothatanyinterestedAsyncListenerinstanceswillbenotified.
TheAsyncListener.
onCompletenotificationshouldalsobeusedbyfiltersasamechanismtoclearupresourcesthatithasbeenholdingontofortheasynctasktocomplete.
Dispatchingfromasynchronousservlettoanasynchronousservletwouldbeillegal.
HoweverthedecisionofthrowinganIllegalStateExceptionisdeferredtothepointwhentheapplicationcallsstartAsync.
Thiswouldallowaservlettoeitherfunctionasasynchronousoranasynchronousservlet.
Theasynctaskthattheapplicationiswaitingforcouldwritedirectlytotheresponse,onadifferentthreadthantheonethatwasusedfortheinitialrequest.
Thisthreadknowsnothingaboutanyfilters.
Ifafilterwantedtomanipulatetheresponseinthenewthread,itwouldhavetowraptheresponsewhenitwasprocessingtheinitialrequest"onthewayin",andpassedthewrappedresponsetothenextfilterinthechain,andeventuallytotheservlet.
Soiftheresponsewaswrapped(possiblymultipletimes,onceperfilter),andtheapplicationprocessestherequestandwritesdirectlytotheresponse,itisreallywritingtotheresponsewrapper(s),i.
e.
,anyoutputaddedtotheresponsewillstillbeprocessedbytheresponsewrapper(s).
Whenanapplicationreadsfromarequestinaseparatethread,andaddsoutputtotheresponse,itreallyreadsfromtherequestwrapper(s),andwritestotheresponsewrapper(s),soanyinputand/oroutputmanipulationintendedbythewrapper(s)willcontinuetooccur.
12JavaServletSpecificationAlternatelyiftheapplicationchoosestodosoitcanusetheAsyncContexttodispatchtherequestfromthenewthreadtoaresourceinthecontainer.
ThiswouldenableusingcontentgenerationtechnologieslikeJSPwithinthescopeofthecontainer.
Inadditiontotheannotationattributeswehavethefollowingmethods/classesadded:ServletRequestpublicAsyncContextstartAsync(ServletRequestreq,ServletResponseres).
Thismethodputstherequestintoasynchronousmodeandinitializesit'sAsyncContextwiththegivenrequestandresponseobjectsandthetimeoutreturnedbygetAsyncTimeout.
TheServletRequestandServletResponseparametersMUSTbeeitherthesameobjectsaswerepassedtothecallingservlet'sservice,orthefilter'sdoFiltermethod,orbesubclassesofServletRequestWrapperorServletResponseWrapperclassesthatwrapthem.
Acalltothismethodensuresthattheresponseisn'tcommittedwhentheapplicationexitsoutoftheservicemethod.
ItiscommittedwhenAsyncContext.
completeiscalledonthereturnedAsyncContextortheAsyncContexttimesoutandtherearenolistenersassociatedtohandlethetimeout.
Thetimerforasynctimeoutswillnotstartuntiltherequestandit'sassociatedresponsehavereturnedfromthecontainer.
TheAsyncContextcouldbeusedtowritetotheresponsefromtheasyncthread.
Itcanalsobeusedtojustnotifythattheresponseisnotclosedandcommitted.
ItisillegaltocallstartAsynciftherequestiswithinthescopeofaservletorfilterthatdoesnotsupportasynchronousoperations,oriftheresponsehasbeencommittedandclosed,oriscalledagainduringthesamedispatch.
TheAsyncContextreturnedfromacalltostartAsynccanthenbeusedforfurtherasynchronousprocessing.
CallingtheAsyncContext.
hasOriginalRequestResponse()onthereturnedAsyncContextwillreturnfalse,unlessthepassedServletRequestandServletResponseargumentsaretheoriginalonesordonotcarryapplicationprovidedwrappers.
AnyfiltersinvokedintheoutbouddirectionafterthisrequestwasputintoasynchronousmodeMAYusethisasanindicationthatsomeoftherequestand/orresponsewrappersthattheyaddedduringtheirinboundinvocationMAYneedtostayinplaceforthedurationoftheasynchronousoperation,andtheirassociatedresourcesMAYnotbereleased.
AServletRequestWrapperappliedduringtheinboundinvocationofafilterMAYbereleasedbytheoutboundinvocationofthefilteronlyifthegivenServletRequestwhichisusedtoinitializetheAsyncContextandwillbereturnedbyacalltoAsyncContext.
getRequest(),doesnotcontainthesaidServletRequestWrapper.
ThesameholdstrueforServletResponseWrapperinstances.
Chapter2TheServletInterface13publicAsyncContextstartAsync()isprovidedasaconveniencethatusestheoriginalrequestandresponseobjectsfortheasyncprocessing.
PleasenoteusersofthismethodSHOULDflushtheresponseiftheyarewrappedbeforecallingthismethodifyouwish,toensurethatanydatawrittentothewrappedresponseisn'tlost.
publicAsyncContextgetAsyncContext()-returnstheAsyncContextthatwascreatedorreinitializedbytheinvocationofstartAsync.
ItisillegaltocallgetAsyncContextiftherequesthasnotbeenputinasynchronousmode.
publicbooleanisAsyncSupported()-Returnstrueiftherequestsupportsasyncprocessing,andfalseotherwise.
Asyncsupportwillbedisabledassoonastherequesthaspassedafilterorservletthatdoesnotsupportasyncprocessing(eitherviathedesignatedannotationordeclaratively).
publicbooleanisAsyncStarted()-Returnstrueifasyncprocessinghasstartedonthisrequest,andfalseotherwise.
IfthisrequesthasbeendispatchedusingoneoftheAsyncContext.
dispatchmethodssinceitwasputinasynchronousmode,oracalltoAsynContext.
completeismade,thismethodreturnsfalse.
publicDispatcherTypegetDispatcherType()-Returnsthedispatchertypeofarequest.
Thedispatchertypeofarequestisusedbythecontainertoselectthefiltersthatneedtobeappliedtotherequest.
Onlyfilterswiththematchingdispatchertypeandurlpatternswillbeapplied.
Allowingafilterthathasbeenconfiguredformultipledispatchertypestoqueryarequestforit'sdispatchertypeallowsthefiltertoprocesstherequestdifferentlydependingonit'sdispatchertype.
TheinitialdispatchertypeofarequestisdefinedasDispatcherType.
REQUEST.
ThedispatchertypeofarequestdispatchedviaRequestDispatcher.
forward(ServletRequest,ServletResponse)orRequestDispatcher.
include(ServletRequest,ServletResponse)isgivenasDispatcherType.
FORWARDorDispatcherType.
INCLUDErespectively,whileadispatchertypeofanasynchronousrequestdispatchedviaoneoftheAsyncContext.
dispatchmethodsisgivenasDispatcherType.
ASYNC.
Finallythedispatchertypeofarequestdispatchedtoanerrorpagebythecontainer'serrorhandlingmechanismisgivenasDispatcherType.
ERROR.
AsyncContext-ThisclassrepresentstheexecutioncontextfortheasynchronousoperationthatwasstartedontheServletRequest.
AnAsyncContextiscreatedandinitializedbyacalltoServletRequest.
startAsyncasdescribedabove.
ThefollowingmethodsareintheAsyncContext:publicServletRequestgetRequest()-returnstherequestthatwasusedtoinitializetheAsyncContextbycallingoneofthestartAsyncmethods.
CallinggetRequestwhencompleteoranyofthedispatchmethodshasbeenpreviouslycalledintheasynchronouscyclewillresultinanIllegalStateException.
publicServletResponsegetResponse()-returnstheresponsethatwasusedtoinitializetheAsyncContextbycallingoneofthestartAsyncmethods.
CallinggetResponsewhencompleteoranyofthedispatchmethodshasbeenpreviouslycalledintheasynchronouscyclewillresultinanIllegalStateException.
14JavaServletSpecificationpublicvoidsetTimeout(longtimeoutMilliseconds)-Setsthetimeoutfortheasynchronousprocessingtooccurinmilliseconds.
Acalltothismethodoverridesthetimeoutsetbythecontainer.
IfthetimeoutisnotspecifiedviathecalltothesetTimeout,thenacontainerdefaultwillbeused.
Avalueof0orlessindicatesthattheasynchronousoperationwillnevertimeout.
ThetimeoutappliestotheAsyncContextoncethecontainer-initiateddispatchduringwhichoneoftheServletRequest.
startAsyncmethodswascalledhasreturnedtothecontainer.
Itisillegaltosetthetimeoutifthismethodiscalledafterthecontainer-initiateddispatchonwhichtheasynchronouscyclewasstartedhasreturnedtothecontainerandwillresultinanIllegalStateException.
publiclonggetTimeout()-Getsthetimeout,inmilliseconds,associatedwiththeAsyncContext.
Thismethodreturnsthecontainer'sdefaulttimeout,orthetimeoutvaluesetviathemostrecentinvocationofsetTimeoutmethod.
publicvoidaddListener(AsyncListenerlistener,ServletRequestreq,ServletResponseres)-RegistersthegivenlistenerfornotificationsofonTimeout,onError,onCompleteoronStartAsync.
ThefirstthreeareassociatedwiththemostrecentasynchronouscyclestartedbycallingoneoftheServletRequest.
startAsyncmethods.
TheonStartAsyncisassociatedtoanewasynchronouscycleviaoneoftheServletRequest.
startAsyncmethods.
Asynclistenerswillbenotifiedintheorderinwhichtheywereaddedtotherequest.
TherequestandresponseobjectspassedintothemethodaretheexactsameonesthatareavailablefromtheAsyncEvent.
getSuppliedRequest()andAsyncEvent.
getSuppliedResponse()whentheAsyncListenerisnotified.
Theseobjectsshouldnotbereadfromorwrittento,becauseadditionalwrappingmayhaveoccurredsincethegivenAsyncListenerwasregistered,butmaybeusedinordertoreleaseanyresourcesassociatedwiththem.
Itisillegaltocallthismethodafterthecontainer-initiateddispatchonwhichtheasynchronouscyclewasstartedhasreturnedtothecontainerandbeforeanewasynchronouscyclewasstartedandwillresultinanIllegalStateException.
publiccreateListener(Classclazz)-InstantiatesthegivenAsyncListenerclass.
ThereturnedAsyncListenerinstancemaybefurthercustomizedbeforeitisregisteredwiththeAsyncContextviaacalltooneoftheaddListenermethodsspecifiedbelow.
ThegivenAsyncListenerclassMUSTdefineazeroargumentconstructor,whichisusedtoinstantiateit.
ThismethodsupportsanyannotationsapplicabletotheAsyncListener.
publicvoidaddListener(AsyncListener)-RegistersthegivenlistenerfornotificationsofonTimeout,onError,onCompleteoronStartAsync.
ThefirstthreeareassociatedwiththemostrecentasynchronouscyclestartedbycallingoneoftheServletRequest.
startAsyncmethods.
TheonStartAsyncisassociatedtoanewasynchronouscycleviaoneoftheServletRequest.
startAsyncmethods.
IfstartAsync(req,res)orstartAsync()iscalledontherequest,theexactsamerequestandresponseobjectsareavailablefromtheAsyncEventwhentheAsyncListenerisnotified.
Therequestandresponsemayormaynotbewrapped.
Asynclistenerswillbenotifiedintheorderinwhichtheywereaddedtotherequest.
Itisillegaltocallthismethodafterthecontainer-initiatedChapter2TheServletInterface15dispatchonwhichtheasynchronouscyclewasstartedhasreturnedtothecontainerandbeforeanewasynchronouscyclewasstartedandwillresultinanIllegalStateException.
publicvoiddispatch(Stringpath)-DispatchestherequestandresponsethatwereusedtoinitializetheAsyncContexttotheresourcewiththegivenpath.
ThegivenpathisinterpretedasrelativetotheServletContextthatinitializedtheAsyncContext.
AllpathrelatedquerymethodsoftherequestMUSTreflectthedispatchtarget,whiletheoriginalrequestURI,contextpath,pathinfoandquerystringmaybeobtainedfromtherequestattributesasdefinedinSection9.
7.
2,"DispatchedRequestParameters"onpage9-100.
TheseattributesMUSTalwaysreflecttheoriginalpathelements,evenaftermultipledispatches.
publicvoiddispatch()-ProvidedasaconveniencetodispatchtherequestandresponseusedtoinitializetheAsyncContextasfollows.
IftheAsyncContextwasinitializedviathestartAsync(ServletRequest,ServletResponse)andtherequestpassedisaninstanceofHttpServletRequest,thenthedispatchistotheURIreturnedbyHttpServletRequest.
getRequestURI().
OtherwisethedispatchistotheURIoftherequestwhenitwaslastdispatchedbythecontainer.
TheexamplesCODEEXAMPLE2-1,CODEEXAMPLE2-2andCODEEXAMPLE2-3shownbelowdemonstratewhatthetargetURIofdispatchwouldbeinthedifferentcases.
CODEEXAMPLE2-1CODEEXAMPLE2-2CODEEXAMPLE2-3//REQUESTto/url/AAsyncContextac=request.
startAsync();.
.
.
ac.
dispatch();//ASYNCdispatchto/url/A//REQUESTto/url/A//FORWARDto/url/Brequest.
getRequestDispatcher("/url/B").
forward(request,response);//StartasyncoperationfromwithinthetargetoftheFORWARDAsyncContextac=request.
startAsync();ac.
dispatch();//ASYNCdispatchto/url/A//REQUESTto/url/A//FORWARDto/url/Brequest.
getRequestDispatcher("/url/B").
forward(request,response);16JavaServletSpecificationpublicvoiddispatch(ServletContextcontext,Stringpath)-dispatchestherequestandresponseusedtoinitializetheAsyncContexttotheresourcewiththegivenpathinthegivenServletContext.
Forallthe3variationsofthedispatchmethodsdefinedabove,callstothemethodsreturnsimmediatelyafterpassingtherequestandresponseobjectstoacontainermanagedthread,onwhichthedispatchoperationwillbeperformed.
ThedispatchertypeoftherequestissettoASYNC.
UnlikeRequestDispatcher.
forward(ServletRequest,ServletResponse)dispatches,theresponsebufferandheaderswillnotbereset,anditislegaltodispatcheveniftheresponsehasalreadybeencommitted.
Controlovertherequestandresponseisdelegatedtothedispatchtarget,andtheresponsewillbeclosedwhenthedispatchtargethascompletedexecution,unlessServletRequest.
startAsync()orServletRequest.
startAsync(ServletRequest,ServletResponse)iscalled.
Ifanyofthedispatchmethodsarecalledbeforethecontainer-initiateddispatchthatcalledstartAsynchasreturnedtothecontainer,thenthecallwillnottakeeffectuntilafterthecontainer-initiateddispatchhasreturnedtothecontainer.
InvocationoftheAsyncListener.
onComplete(AsyncEvent),AsyncListener.
onTimeout(AsyncEvent)andAsyncListener.
onError(AsyncEvent)willalsobedelayedtillafterthecontainer-initiateddispatchhasreturnedtothecontainer.
Therecanbeatmostoneasynchronousdispatchoperationperasynchronouscycle,whichisstartedbyacalltooneoftheServletRequest.
startAsyncmethods.
Therecanbeatmostoneasynchronousdispatchperasynchronouscycle,whichisstartedbyacalltoServletRequest.
startAsync.
AnyattempttoperformadditionalasynchronousdispatchoperationwithinthesameasynchronouscycleisillegalandwillresultinanIllegalStateException.
IfstartAsyncissubsequentlycalledonthedispatchedrequest,thenanyofthedispatchmethodsmaybecalledwiththesamerestrictionasabove.
AnyerrorsorexceptionsthatmayoccurduringtheexecutionofthedispatchmethodsMUSTbecaughtandhandledbythecontainerasfollows:i.
invoketheAsyncListener.
onError(AsyncEvent)methodforallinstancesoftheAsyncListenerregisteredwiththeServletRequestforwhichtheAsyncContextwascreatedandmaketheThrowableavailableviatheAsyncEvent.
getThrowable().
ii.
IfnoneofthelistenerscalledAsyncContext.
completeoranyoftheAsyncContext.
dispatchmethods,thenperformanerrordispatchwithastatuscodeequaltoHttpServletResponse.
SC_INTERNAL_SERVER_ERRORandmaketheThrowableavailableasthevalueoftheRequestDispatcher.
ERROR_EXCEPTIONrequestattribute.
//StartasyncoperationfromwithinthetargetoftheFORWARDAsyncContextac=request.
startAsync(request,response);ac.
dispatch();//ASYNCdispatchto/url/BChapter2TheServletInterface17iii.
Ifnomatchingerrorpageisfound,ortheerrorpagedoesnotcallAsyncContext.
complete()oranyoftheAsyncContext.
dispatchmethods,thenthecontainerMUSTcallAsyncContext.
complete.
publicbooleanhasOriginalRequestAndResponse()-ThismethodchecksiftheAsyncContextwasinitializedwiththeoriginalrequestandresponseobjectsbycallingServletRequest.
startAsync()orifitwasinitializedbycallingServletRequest.
startAsync(ServletRequest,ServletResponse)andneithertheServletRequestnortheServletResponseargumentcarriedanyapplicationprovidedwrappers,inwhichcaseitreturnstrue.
IftheAsyncContextwasinitializedwithwrappedrequestand/orresponseobjectsusingServletRequest.
startAsync(ServletRequest,ServletResponse),itreturnsfalse.
Thisinformationmaybeusedbyfiltersinvokedintheoutbounddirection,afterarequestwasputintoasynchronousmode,todeterminewhetheranyrequestand/orresponsewrappersthattheyaddedduringtheirinboundinvocationneedtobepreservedforthedurationoftheasynchronousoperationormaybereleased.
publicvoidstart(Runnabler)-Thismethodcausesthecontainertodispatchathread,possiblyfromamanagedthreadpool,torunthespecifiedRunnable.
ThecontainermaypropagateappropriatecontextualinformationtotheRunnable.
publicvoidcomplete()-Ifrequest.
startAsynciscalledthenthismethodMUSTbecalledtocompletetheasyncprocessingandcommitandclosetheresponse.
Thecompletemethodcanbeinvokedbythecontaineriftherequestisdispatchedtoaservletthatdoesnotsupportasyncprocessing,orthetargetservletcalledbyAsyncContext.
dispatchdoesnotdoasubsequentcalltostartAsync.
Inthiscase,itisthecontainer'sresponsibilitytocallcomplete()assoonasthatservlet'sservicemethodisexited.
AnIllegalStateExceptionMUSTbethrownifstartAsyncwasnotcalled.
ItislegaltocallthismethodanytimeafteracalltoServletRequest.
startAsync()orServletRequest.
startAsync(ServletRequest,ServletResponse)andbeforeacalltooneofthedispatchmethods.
Ifthismethodiscalledbeforethecontainer-initiateddispatchthatcalledstartAsynchasreturnedtothecontainer,thenthecallwillnottakeeffectuntilafterthecontainer-initiateddispatchhasreturnedtothecontainer.
InvocationoftheAsyncListener.
onComplete(AsyncEvent)willalsobedelayedtillafterthecontainer-initiateddispatchhasreturnedtothecontainer.
ServletRequestWrapperpublicbooleanisWrapperFor(ServletRequestreq)-ChecksrecursivelyifthiswrapperwrapsthegivenServletRequestandreturnstrueifitdoes,elseitreturnsfalseServletResponseWrapperpublicbooleanisWrapperFor(ServletResponseres)-ChecksrecursivelyifthiswrapperwrapsthegivenServletResponseandreturnstrueifitdoes,elseitreturnsfalse.
AsyncListener18JavaServletSpecificationpublicvoidonComplete(AsyncEventevent)-IsusedtonotifythelistenerofcompletionoftheasynchronousoperationstartedontheServletRequest.
publicvoidonTimeout(AsyncEventevent)-IsusedtonotifythelistenerofatimeoutoftheasynchronousoperationstartedontheServletRequest.
publicvoidonError(AsyncEventevent)-Isusedtonotifythelistenerthattheasynchronousoperationhasfailedtocomplete.
publicvoidonStartAsync(AsyncEventevent)-IsusedtonotifythelistenerthatanewasynchronouscycleisbeinginitiatedviaacalltooneoftheServletRequest.
startAsyncmethods.
TheAsyncContextcorrespondingtotheasynchronousoperationthatisbeingreinitializedmaybeobtainedbycallingAsyncEvent.
getAsyncContextonthegivenevent.
Intheeventthatanasynchronousoperationtimesout,thecontainermustrunthroughthefollowingsteps:InvoketheAsyncListener.
onTimeoutmethodonalltheAsyncListenerinstancesregisteredwiththeServletRequestonwhichtheasynchronousoperationwasinitiated.
IfnoneofthelistenerscalledAsyncContext.
complete()oranyoftheAsyncContext.
dispatchmethods,performanerrordispatchwithastatuscodeequaltoHttpServletResponse.
SC_INTERNAL_SERVER_ERROR.
Ifnomatchingerrorpagewasfound,ortheerrorpagedidnotcallAsyncContext.
complete()oranyoftheAsyncContext.
dispatchmethods,thecontainerMUSTcallAsyncContext.
complete().
IfanexceptionisthrownwhileinvokingmethodsinanAsyncListener,itisloggedandwillnotaffecttheinvocationofanyotherAsyncListeners.
AsyncprocessinginJSPwouldnotbesupportedbydefaultasitisusedforcontentgenerationandasyncprocessingwouldhavetobedonebeforethecontentgeneration.
Itisuptothecontainerhowtohandlethiscase.
Oncealltheasyncactivitiesaredone,adispatchtotheJSPpageusingtheAsyncContext.
dispatchcanbeusedforgeneratingcontent.
Figure2-1shownbelowisadiagramdepictingthestatetransitionsforvariousasynchronousoperations.
Chapter2TheServletInterface19FIGURE2-1Statetransitiondiagramforasynchronousoperations20JavaServletSpecification2.
3.
3.
4ThreadSafetyOtherthanthestartAsyncandcompletemethods,implementationsoftherequestandresponseobjectsarenotguaranteedtobethreadsafe.
Thismeansthattheyshouldeitheronlybeusedwithinthescopeoftherequesthandlingthreadortheapplicationmustensurethataccesstotherequestandresponseobjectsarethreadsafe.
Ifathreadcreatedbytheapplicationusesthecontainer-managedobjects,suchastherequestorresponseobject,thoseobjectsmustbeaccessedonlywithintheobject'slifecycleasdefinedinsectionsSection3.
12,"LifetimeoftheRequestObject"onpage3-31andSection5.
7,"LifetimeoftheResponseObject"onpage5-50respectively.
BeawarethatotherthanthestartAsync,andcompletemethods,therequestandresponseobjectsarenotthreadsafe.
Ifthoseobjectswereaccessedinthemultiplethreads,theaccessshouldbesynchronizedorbedonethroughawrappertoaddthethreadsafety,forinstance,synchronizingthecallofthemethodstoaccesstherequestattribute,orusingalocaloutputstreamfortheresponseobjectwithinathread.
2.
3.
3.
5UpgradeProcessingInHTTP/1.
1,theUpgradegeneral-headerallowstheclienttospecifytheadditionalcommunicationprotocolsthatitsupportsandwouldliketouse.
Iftheserverfindsitappropriatetoswitchprotocols,thennewprotocolswillbeusedinsubsequentcommunication.
TheservletcontainerprovidesanHTTPupgrademechanism.
Howevertheservletcontaineritselfdoesnothaveknowledgeabouttheupgradedprotocol.
TheprotocolprocessingisencapsulatedintheHttpUpgradeHandler.
DatareadingorwritingbetweentheservletcontainerandtheHttpUpgradeHandlerisinbytestreams.
Whenanupgraderequestisreceived,theservletcaninvoketheHttpServletRequest.
upgrademethod,whichstartstheupgradeprocess.
ThismethodinstantiatesthegivenHttpUpgradeHandlerclass.
ThereturnedHttpUpgradeHandlerinstancemaybefurthercustomized.
Theapplicationpreparesandsendsanappropriateresponsetotheclient.
Afterexitingtheservicemethodoftheservlet,theservletcontainercompletestheprocessingofallfiltersandmarkstheconnectiontobehandledbytheHttpUpgradeHandler.
ItthencallstheHttpUpgradeHandler'sinitmethod,passingaWebConnectiontoallowtheprotocolhandleraccesstothedatastreams.
TheservletfiltersonlyprocesstheinitialHTTPrequestandresponse.
Theyarenotinvolvedinsubsequentcommunications.
Inotherwords,theyarenotinvokedoncetherequesthasbeenupgraded.
Chapter2TheServletInterface21TheHttpUpgradeHandlermayusenonblockingIOtoconsumeandproducemessages.
TheDeveloperhastheresponsibilityforthreadsafeaccesstotheServletInputStreamandServletOutputStreamwhileprocessingHTTPupgrade.
Whentheupgradeprocessingisdone,HttpUpgradeHandler.
destroywillbeinvoked.
2.
3.
4EndofServiceTheservletcontainerisnotrequiredtokeepaservletloadedforanyparticularperiodoftime.
Aservletinstancemaybekeptactiveinaservletcontainerforaperiodofmilliseconds,forthelifetimeoftheservletcontainer(whichcouldbeanumberofdays,months,oryears),oranyamountoftimeinbetween.
Whentheservletcontainerdeterminesthataservletshouldberemovedfromservice,itcallsthedestroymethodoftheServletinterfacetoallowtheservlettoreleaseanyresourcesitisusingandsaveanypersistentstate.
Forexample,thecontainermaydothiswhenitwantstoconservememoryresources,orwhenitisbeingshutdown.
Beforetheservletcontainercallsthedestroymethod,itmustallowanythreadsthatarecurrentlyrunningintheservicemethodoftheservlettocompleteexecution,orexceedaserver-definedtimelimit.
Oncethedestroymethodiscalledonaservletinstance,thecontainermaynotrouteotherrequeststothatinstanceoftheservlet.
Ifthecontainerneedstoenabletheservletagain,itmustdosowithanewinstanceoftheservlet'sclass.
Afterthedestroymethodcompletes,theservletcontainermustreleasetheservletinstancesothatitiseligibleforgarbagecollection.
22JavaServletSpecification23CHAPTER3TheRequestTherequestobjectencapsulatesallinformationfromtheclientrequest.
IntheHTTPprotocol,thisinformationistransmittedfromtheclienttotheserverintheHTTPheadersandthemessagebodyoftherequest.
3.
1HTTPProtocolParametersRequestparametersfortheservletarethestringssentbytheclienttoaservletcontaineraspartofitsrequest.
WhentherequestisanHttpServletRequestobject,andconditionssetoutin"WhenParametersAreAvailable"onpage24aremet,thecontainerpopulatestheparametersfromtheURIquerystringandPOST-eddata.
Theparametersarestoredasasetofname-valuepairs.
Multipleparametervaluescanexistforanygivenparametername.
ThefollowingmethodsoftheServletRequestinterfaceareavailabletoaccessparameters:getParametergetParameterNamesgetParameterValuesgetParameterMapThegetParameterValuesmethodreturnsanarrayofStringobjectscontainingalltheparametervaluesassociatedwithaparametername.
ThevaluereturnedfromthegetParametermethodmustbethefirstvalueinthearrayofStringobjectsreturnedbygetParameterValues.
ThegetParameterMapmethodreturnsajava.
util.
Mapoftheparameteroftherequest,whichcontainsnamesaskeysandparametervaluesasmapvalues.
Datafromthequerystringandthepostbodyareaggregatedintotherequestparameterset.
Querystringdataispresentedbeforepostbodydata.
Forexample,ifarequestismadewithaquerystringofa=helloandapostbodyofa=goodbye&a=world,theresultingparametersetwouldbeordereda=(hello,goodbye,world).
24JavaServletSpecificationPathparametersthatarepartofaGETrequest(asdefinedbyHTTP1.
1)arenotexposedbytheseAPIs.
TheymustbeparsedfromtheStringvaluesreturnedbythegetRequestURImethodorthegetPathInfomethod.
3.
1.
1WhenParametersAreAvailableThefollowingaretheconditionsthatmustbemetbeforepostformdatawillbepopulatedtotheparameterset:1.
TherequestisanHTTPorHTTPSrequest.
2.
TheHTTPmethodisPOST.
3.
Thecontenttypeisapplication/x-www-form-urlencoded.
4.
TheservlethasmadeaninitialcallofanyofthegetParameterfamilyofmethodsontherequestobject.
Iftheconditionsarenotmetandthepostformdataisnotincludedintheparameterset,thepostdatamuststillbeavailabletotheservletviatherequestobject'sinputstream.
Iftheconditionsaremet,postformdatawillnolongerbeavailableforreadingdirectlyfromtherequestobject'sinputstream.
3.
2FileuploadServletcontainerallowsfilestobeuploadedwhendataissentasmultipart/form-data.
Theservletcontainerprovidesmultipart/form-dataprocessingifanyoneofthefollowingconditionsismet.
Theservlethandlingtherequestisannotatedwiththe@MultipartConfigasdefinedinSection8.
1.
5,"@MultipartConfig"onpage8-70.
Deploymentdescriptorscontainamultipart-configelementfortheservlethandlingtherequest.
Howdatainarequestoftypemultipart/form-dataismadeavailabledependsonwhethertheservletcontainerprovidesmultipart/form-dataprocessing:Iftheservletcontainerprovidesmultipart/form-dataprocessing,thedataismadeavailablethroughthefollowingmethodsinHttpServletRequest:publicCollectiongetParts()publicPartgetPart(Stringname)Chapter3TheRequest25Eachpartprovidesaccesstotheheaders,contenttyperelatedwithitandthecontentviathePart.
getInputStreammethod.
Forpartswithform-dataastheContent-Disposition,butwithoutafilename,thestringvalueofthepartwillalsobeavailablethroughthegetParameterandgetParameterValuesmethodsonHttpServletRequest,usingthenameofthepart.
Iftheservletcontainerdoesnotprovidethemulti-part/form-dataprocessing,thedatawillbeavailablethroughtheHttpServletReuqest.
getInputStream.
3.
3AttributesAttributesareobjectsassociatedwitharequest.
AttributesmaybesetbythecontainertoexpressinformationthatotherwisecouldnotbeexpressedviatheAPI,ormaybesetbyaservlettocommunicateinformationtoanotherservlet(viatheRequestDispatcher).
AttributesareaccessedwiththefollowingmethodsoftheServletRequestinterface:getAttributegetAttributeNamessetAttributeOnlyoneattributevaluemaybeassociatedwithanattributename.
Attributenamesbeginningwiththeprefixesofjava.
andjavax.
arereservedfordefinitionbythisspecification.
Similarly,attributenamesbeginningwiththeprefixesofsun.
,com.
sun.
,oracleandcom.
oraclearereservedfordefinitionbyOracleCorporation.
ItissuggestedthatallattributesplacedintheattributesetbenamedinaccordancewiththereversedomainnameconventionsuggestedbytheJavaProgrammingLanguageSpecification1forpackagenaming.
3.
4HeadersAservletcanaccesstheheadersofanHTTPrequestthroughthefollowingmethodsoftheHttpServletRequestinterface:getHeadergetHeadersgetHeaderNames1.
TheJavaProgrammingLanguageSpecificationisavailableathttp://docs.
oracle.
com/javase/specs/26JavaServletSpecificationThegetHeadermethodreturnsaheadergiventhenameoftheheader.
Therecanbemultipleheaderswiththesamename,e.
g.
Cache-Controlheaders,inanHTTPrequest.
Iftherearemultipleheaderswiththesamename,thegetHeadermethodreturnsthefirstheaderintherequest.
ThegetHeadersmethodallowsaccesstoalltheheadervaluesassociatedwithaparticularheadername,returninganEnumerationofStringobjects.
HeadersmaycontainStringrepresentationsofintorDatedata.
ThefollowingconveniencemethodsoftheHttpServletRequestinterfaceprovideaccesstoheaderdatainaoneoftheseformats:getIntHeadergetDateHeaderIfthegetIntHeadermethodcannottranslatetheheadervaluetoanint,aNumberFormatExceptionisthrown.
IfthegetDateHeadermethodcannottranslatetheheadertoaDateobject,anIllegalArgumentExceptionisthrown.
3.
5RequestPathElementsTherequestpaththatleadstoaservletservicingarequestiscomposedofmanyimportantsections.
ThefollowingelementsareobtainedfromtherequestURIpathandexposedviatherequestobject:ContextPath:ThepathprefixassociatedwiththeServletContextthatthisservletisapartof.
Ifthiscontextisthe"default"contextrootedatthebaseoftheWebserver'sURLnamespace,thispathwillbeanemptystring.
Otherwise,ifthecontextisnotrootedattherootoftheserver'snamespace,thepathstartswitha/characterbutdoesnotendwitha/character.
ServletPath:Thepathsectionthatdirectlycorrespondstothemappingwhichactivatedthisrequest.
Thispathstartswitha'/'characterexceptinthecasewheretherequestismatchedwiththe'/*'or""pattern,inwhichcaseitisanemptystring.
PathInfo:ThepartoftherequestpaththatisnotpartoftheContextPathortheServletPath.
Itiseithernullifthereisnoextrapath,orisastringwithaleading'/'.
ThefollowingmethodsexistintheHttpServletRequestinterfacetoaccessthisinformation:getContextPathgetServletPathgetPathInfoItisimportanttonotethat,exceptforURLencodingdifferencesbetweentherequestURIandthepathparts,thefollowingequationisalwaystrue:Chapter3TheRequest27requestURI=contextPath+servletPath+pathInfoTogiveafewexamplestoclarifytheabovepoints,considerthefollowing:Thefollowingbehaviorisobserved:3.
6PathTranslationMethodsTherearetwoconveniencemethodsintheAPIwhichallowtheDevelopertoobtainthefilesystempathequivalenttoaparticularpath.
Thesemethodsare:ServletContext.
getRealPathHttpServletRequest.
getPathTranslatedThegetRealPathmethodtakesaStringargumentandreturnsaStringrepresentationofafileonthelocalfilesystemtowhichapathcorresponds.
ThegetPathTranslatedmethodcomputestherealpathofthepathInfooftherequest.
TABLE3-1ExampleContextSetUpContextPath/catalogServletMappingPattern:/lawn/*Servlet:LawnServletServletMappingPattern:/garden/*Servlet:GardenServletServletMappingPattern:*.
jspServlet:JSPServletTABLE3-2ObservedPathElementBehaviorRequestPathPathElements/catalog/lawn/index.
htmlContextPath:/catalogServletPath:/lawnPathInfo:/index.
html/catalog/garden/implements/ContextPath:/catalogServletPath:/gardenPathInfo:/implements//catalog/help/feedback.
jspContextPath:/catalogServletPath:/help/feedback.
jspPathInfo:null28JavaServletSpecificationInsituationswheretheservletcontainercannotdetermineavalidfilepathforthesemethods,suchaswhentheWebapplicationisexecutedfromanarchive,onaremotefilesystemnotaccessiblelocally,orinadatabase,thesemethodsmustreturnnull.
ResourcesinsidetheMETA-INF/resourcesdirectoryofJARfilemustbeconsideredonlyifthecontainerhasunpackedthemfromtheircontainingJARfilewhenacalltogetRealPath()ismade,andinthiscaseMUSTreturntheunpackedlocation.
3.
7NonBlockingIONon-blockingrequestprocessingintheWebContainerhelpsimprovetheeverincreasingdemandforimprovedWebContainerscalability,increasethenumberofconnectionsthatcansimultaneouslybehandledbytheWebContainer.
Non-blockingIOintheServletcontainerallowsdeveloperstoreaddataasitbecomesavailableorwritedatawhenpossibletodoso.
Non-blockingIOonlyworkswithasyncrequestprocessinginServletsandFilters(asdefinedinSection2.
3.
3.
3,"Asynchronousprocessing"onpage2-10),andupgradeprocessing(asdefinedinSection2.
3.
3.
5,"UpgradeProcessing"onpage2-20).
Otherwise,anIllegalStateExceptionmustbethrownwhenServletInputStream.
setReadListenerorServletOutputStream.
setWriteListenerisinvoked.
TheReadListenerprovidesthefollowingcallbackmethodsfornonblockingIO-ReadListeneronDataAvailable().
TheonDataAvailablemethodisinvokedontheReadListenerwhendataisavailabletoreadfromtheincomingrequeststream.
Thecontainerwillinvokethemethodthefirsttimewhendataisavailabletoread.
ThecontainerwillsubsequentlyinvoketheonDataAvailablemethodifandonlyifisReadymethodonServletInputStream,describedbelow,returnsfalse.
onAllDataRead().
TheonAllDataReadmethodisinvokedwhenyouhavefinishedreadingallthedatafortheServletRequestforwhichthelistenerwasregistered.
onError(Throwablet).
TheonErrormethodisinvokedifthereisanyerrororexceptionthatoccurswhileprocessingtherequest.
TheServletcontainermustaccessmethodsinReadListenerinathreadsafemanner.
InadditiontotheReadListenerdefinedabove,thefollowingmethodshavebeenaddedtoServletInputStreamclass-ServletInputStreamChapter3TheRequest29booleanisFinished().
TheisFinishedmethodreturnstruewhenallthedatafortherequestassociatedwiththeServletInputStreamhasbeenread.
Otherwiseitreturnsfalse.
booleanisReady().
TheisReadymethodreturnstrueifdatacanbereadwithoutblocking.
Ifnodatacanbereadwithoutblockingitreturnsfalse.
IfisReadyreturnsfalseitisillegaltocallthereadmethodandanIllegalStateExceptionMUSTbethrown.
voidsetReadListener(ReadListenerlistener).
SetstheReadListenerdefinedabovetogetinvokedtoreaddatainanon-blockingfashion.
OncethelistenerisassociatedforthegivenServletInputStream,thecontainerinvokesthemethodsontheReadListenerwhendataisavailabletoread,allthedatahasbeenreadoriftherewasanerrorprocessingtherequest.
RegisteringaReadListenerwillstartnon-blockingIO.
ItisillegaltoswitchtothetraditionalblockingIOatthatpointandanIllegalStateExceptionMUSTbethrown.
AsubsequentcalltosetReadListenerinthescopeofthecurrentrequestisillegalandanIllegalStateExceptionMUSTbethrown.
3.
8CookiesTheHttpServletRequestinterfaceprovidesthegetCookiesmethodtoobtainanarrayofcookiesthatarepresentintherequest.
Thesecookiesaredatasentfromtheclienttotheserveroneveryrequestthattheclientmakes.
Typically,theonlyinformationthattheclientsendsbackaspartofacookieisthecookienameandthecookievalue.
Othercookieattributesthatcanbesetwhenthecookieissenttothebrowser,suchascomments,arenottypicallyreturned.
ThespecificationalsoallowsforthecookiestobeHttpOnlycookies.
HttpOnlycookiesindicatetotheclientthattheyshouldnotbeexposedtoclient-sidescriptingcode(It'snotfilteredoutunlesstheclientknowstolookforthisattribute).
TheuseofHttpOnlycookieshelpsmitigatecertainkindsofcross-sitescriptingattacks.
30JavaServletSpecification3.
9SSLAttributesIfarequesthasbeentransmittedoverasecureprotocol,suchasHTTPS,thisinformationmustbeexposedviatheisSecuremethodoftheServletRequestinterface.
TheWebcontainermustexposethefollowingattributestotheservletprogrammer:IfthereisanSSLcertificateassociatedwiththerequest,itmustbeexposedbytheservletcontainertotheservletprogrammerasanarrayofobjectsoftypejava.
security.
cert.
X509CertificateandaccessibleviaaServletRequestattributeofjavax.
servlet.
request.
X509Certificate.
Theorderofthisarrayisdefinedasbeinginascendingorderoftrust.
Thefirstcertificateinthechainistheonesetbytheclient,thenextistheoneusedtoauthenticatethefirst,andsoon.
3.
10InternationalizationClientsmayoptionallyindicatetoaWebserverwhatlanguagetheywouldprefertheresponsebegivenin.
ThisinformationcanbecommunicatedfromtheclientusingtheAccept-LanguageheaderalongwithothermechanismsdescribedintheHTTP/1.
1specification.
ThefollowingmethodsareprovidedintheServletRequestinterfacetodeterminethepreferredlocaleofthesender:getLocalegetLocalesThegetLocalemethodwillreturnthepreferredlocaleforwhichtheclientwantstoacceptcontent.
Seesection14.
4ofRFC2616(HTTP/1.
1)formoreinformationabouthowtheAccept-Languageheadermustbeinterpretedtodeterminethepreferredlanguageoftheclient.
TABLE3-3ProtocolAttributesAttributeAttributeNameJavaTypeciphersuitejavax.
servlet.
request.
cipher_suiteStringbitsizeofthealgorithmjavax.
servlet.
request.
key_sizeIntegerSSLsessionidjavax.
servlet.
request.
ssl_session_idStringChapter3TheRequest31ThegetLocalesmethodwillreturnanEnumerationofLocaleobjectsindicating,indecreasingorderstartingwiththepreferredlocale,thelocalesthatareacceptabletotheclient.
Ifnopreferredlocaleisspecifiedbytheclient,thelocalereturnedbythegetLocalemethodmustbethedefaultlocalefortheservletcontainerandthegetLocalesmethodmustcontainanenumerationofasingleLocaleelementofthedefaultlocale.
3.
11RequestdataencodingCurrently,manybrowsersdonotsendacharencodingqualifierwiththeContent-Typeheader,leavingopenthedeterminationofthecharacterencodingforreadingHTTPrequests.
ThedefaultencodingofarequestthecontainerusestocreatetherequestreaderandparsePOSTdatamustbe"ISO-8859-1"ifnonehasbeenspecifiedbytheclientrequest.
However,inordertoindicatetothedeveloper,inthiscase,thefailureoftheclienttosendacharacterencoding,thecontainerreturnsnullfromthegetCharacterEncodingmethod.
Iftheclienthasn'tsetcharacterencodingandtherequestdataisencodedwithadifferentencodingthanthedefaultasdescribedabove,breakagecanoccur.
Toremedythissituation,anewmethodsetCharacterEncoding(Stringenc)hasbeenaddedtotheServletRequestinterface.
Developerscanoverridethecharacterencodingsuppliedbythecontainerbycallingthismethod.
Itmustbecalledpriortoparsinganypostdataorreadinganyinputfromtherequest.
Callingthismethodoncedatahasbeenreadwillnotaffecttheencoding.
3.
12LifetimeoftheRequestObjectEachrequestobjectisvalidonlywithinthescopeofaservlet'sservicemethod,orwithinthescopeofafilter'sdoFiltermethod,unlesstheasynchronousprocessingisenabledforthecomponentandthestartAsyncmethodisinvokedontherequestobject.
Inthecasewhereasynchronousprocessingoccurs,therequestobjectremainsvaliduntilcompleteisinvokedontheAsyncContext.
Containerscommonlyrecyclerequestobjectsinordertoavoidtheperformanceoverheadofrequestobjectcreation.
ThedevelopermustbeawarethatmaintainingreferencestorequestobjectsforwhichstartAsynchasnotbeencalledoutsidethescopedescribedaboveisnotrecommendedasitmayhaveindeterminateresults.
Incaseofupgrade,theaboveisstilltrue.
32JavaServletSpecification33CHAPTER4ServletContext4.
1IntroductiontotheServletContextInterfaceTheServletContextinterfacedefinesaservlet'sviewoftheWebapplicationwithinwhichtheservletisrunning.
TheContainerProviderisresponsibleforprovidinganimplementationoftheServletContextinterfaceintheservletcontainer.
UsingtheServletContextobject,aservletcanlogevents,obtainURLreferencestoresources,andsetandstoreattributesthatotherservletsinthecontextcanaccess.
AServletContextisrootedataknownpathwithinaWebserver.
Forexample,aservletcontextcouldbelocatedathttp://www.
mycorp.
com/catalog.
Allrequeststhatbeginwiththe/catalogrequestpath,knownasthecontextpath,areroutedtotheWebapplicationassociatedwiththeServletContext.
4.
2ScopeofaServletContextInterfaceThereisoneinstanceobjectoftheServletContextinterfaceassociatedwitheachWebapplicationdeployedintoacontainer.
Incaseswherethecontainerisdistributedovermanyvirtualmachines,aWebapplicationwillhaveaninstanceoftheServletContextforeachJVM.
34JavaServletSpecificationServletsinacontainerthatwerenotdeployedaspartofaWebapplicationareimplicitlypartofa"default"WebapplicationandhaveadefaultServletContext.
Inadistributedcontainer,thedefaultServletContextisnon-distributableandmustonlyexistinoneJVM.
4.
3InitializationParametersThefollowingmethodsoftheServletContextinterfaceallowtheservletaccesstocontextinitializationparametersassociatedwithaWebapplicationasspecifiedbytheApplicationDeveloperinthedeploymentdescriptor:getInitParametergetInitParameterNamesInitializationparametersareusedbyanApplicationDevelopertoconveysetupinformation.
TypicalexamplesareaWebmaster'se-mailaddress,orthenameofasystemthatholdscriticaldata.
4.
4ConfigurationmethodsThefollowingmethodsareaddedtoServletContextsinceServlet3.
0toenableprogrammaticdefinitionofservlets,filtersandtheurlpatternthattheymapto.
ThesemethodscanonlybecalledduringtheinitializationoftheapplicationeitherfromthecontexInitializedmethodofaServletContextListenerimplementationorfromtheonStartupmethodofaServletContainerInitializerimplementation.
InadditiontoaddingServletsandFilters,onecanalsolookupaninstanceofaRegistrationobjectcorrespondingtoaServletorFilteroramapofalltheRegistrationobjectsfortheServletsorFilters.
IftheServletContextpassedtotheServletContextListener'scontextInitializedmethodwheretheServletContextListenerwasneitherdeclaredinweb.
xmlorweb-fragment.
xmlnorannotatedwith@WebListenerthenanUnsupportedOperationExceptionMUSTbethrownforallthemethodsdefinedinServletContextforprogrammaticconfigurationofservlets,filtersandlisteners.
Chapter4ServletContext354.
4.
1ProgrammaticallyaddingandconfiguringServletsTheabilitytoprogrammaticallyaddaservlettoacontextisusefulforframeworkdevelopers.
Forexampleaframeworkcoulddeclareacontrollerservletusingthismethod.
ThereturnvalueofthismethodisaServletRegistrationoraServletRegistration.
Dynamicobjectwhichfurtherallowsyoutosetuptheotherparametersoftheservletlikeinit-params,url-mappingsetc.
Therearethreeoverloadedversionsofthemethodasdescribedbelow.
4.
4.
1.
1addServlet(StringservletName,StringclassName)Thismethodallowstheapplicationtodeclareaservletprogrammatically.
Itaddstheservletwiththegivenname,andclassnametotheservletcontext.
4.
4.
1.
2addServlet(StringservletName,Servletservlet)Thismethodallowstheapplicationtodeclareaservletprogrammatically.
Itaddstheservletwiththegivenname,andservletinstancetotheservletcontext.
4.
4.
1.
3addServlet(StringservletName,ClassservletClass)Thismethodallowstheapplicationtodeclareaservletprogrammatically.
Itaddstheservletwiththegivenname,andaninstanceoftheservletclasstotheservletcontext.
4.
4.
1.
4TcreateServlet(Classclazz)ThismethodinstantiatesthegivenServletclass.
ThemethodmustsupportalltheannotationsapplicabletoServletsexcept@WebServlet.
ThereturnedServletinstancemaybefurthercustomizedbeforeitisregisteredwiththeServletContextviaacalltoaddServlet(String,Servlet)asdefinedabove.
36JavaServletSpecification4.
4.
1.
5ServletRegistrationgetServletRegistration(StringservletName)ThismethodreturnstheServletRegistrationcorrespondingtotheservletwiththegivenname,ornullifnoServletRegistrationexistsunderthatname.
AnUnsupportedOperationExceptionisthrowniftheServletContextwaspassedtothecontextInitializedmethodofaServletContextListenerthatwasneitherdeclaredintheweb.
xmlorweb-fragment.
xml,norannotatedwithjavax.
servlet.
annotation.
WebListener.
4.
4.
1.
6MapgetServletRegistrations()ThismethodreturnsamapofServletRegistrationobjects,keyedbynamecorrespondingtoallservletsregisteredwiththeServletContext.
IftherearenoservletsregisteredwiththeServletContextanemptymapisreturned.
ThereturnedMapincludestheServletRegistrationobjectscorrespondingtoalldeclaredandannotatedservlets,aswellastheServletRegistrationobjectscorrespondingtoallservletsthathavebeenaddedviaoneoftheaddServletmethods.
AnychangestothereturnedMapMUSTnotaffecttheServletContext.
AnUnsupportedOperationExceptionisthrowniftheServletContextwaspassedtothecontextInitializedmethodofaServletContextListenerthatwasneitherdeclaredintheweb.
xmlorweb-fragment.
xml,norannotatedwithjavax.
servlet.
annotation.
WebListener.
4.
4.
2ProgrammaticallyaddingandconfiguringFilters4.
4.
2.
1addFilter(StringfilterName,StringclassName)Thismethodallowstheapplicationtodeclareafilterprogrammatically.
Itaddsthefilterwiththegivenname,andclassnametothewebapplication.
4.
4.
2.
2addFilter(StringfilterName,Filterfilter)Thismethodallowstheapplicationtodeclareafilterprogrammatically.
Itaddsthefilterwiththegivenname,andfilterinstancetothewebapplication.
Chapter4ServletContext374.
4.
2.
3addFilter(StringfilterName,ClassfilterClass)Thismethodallowstheapplicationtodeclareafilterprogrammatically.
Itaddsthefilterwiththegivenname,andaninstanceofthefilterclasstothewebapplication.
4.
4.
2.
4TcreateFilter(Classclazz)ThismethodinstantiatesthegivenFilterclass.
ThemethodmustsupportalltheannotationsapplicabletoFilters.
ThereturnedFilterinstancemaybefurthercustomizedbeforeitisregisteredwiththeServletContextviaacalltoaddFilter(String,Filter)asdefinedabove.
ThegivenFilterclassmustdefineazeroargumentconstructor,whichisusedtoinstantiateit.
4.
4.
2.
5FilterRegistrationgetFilterRegistration(StringfilterName)ThismethodreturnstheFilterRegistrationcorrespondingtothefilterwiththegivenname,ornullifnoFilterRegistrationexistsunderthatname.
AnUnsupportedOperationExceptionisthrowniftheServletContextwaspassedtothecontextInitializedmethodofaServletContextListenerthatwasneitherdeclaredintheweb.
xmlorweb-fragment.
xml,norannotatedwithjavax.
servlet.
annotation.
WebListener.
4.
4.
2.
6MapgetServletRegistrations()ThismethodreturnsamapofServletRegistrationobjects,keyedbynamecorrespondingtoallfiltersregisteredwiththeServletContext.
IftherearenofiltersregisteredwiththeServletContextanemptyMapisreturned.
ThereturnedMapincludestheFilterRegistrationobjectscorrespondingtoalldeclaredandannotatedfilters,aswellastheFilterRegistrationobjectscorrespondingtoallfiltersthathavebeenaddedviaoneoftheaddFiltermethods.
AnychangestothereturnedMapMUSTnotaffecttheServletContext.
AnUnsupportedOperationExceptionisthrowniftheServletContextwaspassedtothecontextInitializedmethodofaServletContextListenerthatwasneitherdeclaredintheweb.
xmlorweb-fragment.
xml,norannotatedwithjavax.
servlet.
annotation.
WebListener.
38JavaServletSpecification4.
4.
3ProgrammaticallyaddingandconfiguringListeners4.
4.
3.
1voidaddListener(StringclassName)AddthelistenerwiththegivenclassnametotheServletContext.
TheclasswiththegivennamewillbeloadedusingtheclassloaderassociatedwiththeapplicationrepresentedbytheServletContext,andMUSTimplementoneormoreofthefollowinginterfaces:javax.
servlet.
ServletContextAttributeListenerjavax.
servlet.
ServletRequestListenerjavax.
servlet.
ServletRequestAttributeListenerjavax.
servlet.
http.
HttpSessionListenerjavax.
servlet.
http.
HttpSessionAttributeListenerjavax.
servlet.
http.
HttpSessionIdListenerIftheServletContextwaspassedtotheServletContainerInitializer'sonStartupmethod,thentheclasswiththegivennameMAYalsoimplementjavax.
servlet.
ServletContextListenerinadditiontotheinterfaceslistedabove.
Aspartofthismethodcall,thecontainerMUSTloadtheclasswiththespecifiedclassnametoensurethatitimplementsoneoftherequiredinterfaces.
Iftheclasswiththegivennameimplementsalistenerinterfacewhoseinvocationordercorrespondstothedeclarationorder,thatis,ifitimplementsjavax.
servlet.
ServletRequestListener,javax.
servlet.
ServletContextListenerorjavax.
servlet.
http.
HttpSessionListener,thenthenewlistenerwillbeaddedtotheendoftheorderedlistoflistenersofthatinterface.
4.
4.
3.
2voidaddListener(Tt)AddthegivenlistenertotheServletContext.
ThegivenlistenerMUSTbeaninstanceofoneormoreofthefollowinginterfaces:javax.
servlet.
ServletContextAttributeListenerjavax.
servlet.
ServletRequestListenerjavax.
servlet.
ServletRequestAttributeListenerjavax.
servlet.
http.
HttpSessionListenerjavax.
servlet.
http.
HttpSessionAttributeListenerjavax.
servlet.
http.
HttpSessionIdListenerChapter4ServletContext39IftheServletContextwaspassedtotheServletContainerInitializer'sonStartupmethod,thenthegivenlistenerMAYalsobeaninstanceofjavax.
servlet.
ServletContextListenerinadditiontotheinterfaceslistedabove.
Ifthegivenlistenerisaninstanceofalistenerinterfacewhoseinvocationordercorrespondstothedeclarationorder,thatis,ifitimplementsjavax.
servlet.
ServletRequestListener,javax.
servlet.
ServletContextListenerorjavax.
servlet.
http.
HttpSessionListener,thenthenewlistenerwillbeaddedtotheendoftheorderedlistoflistenersofthatinterface.
4.
4.
3.
3voidaddListener(ClasslistenerClass)AddthelistenerofthegivenclasstypetotheServletContext.
ThegivenlistenerclassMUSTimplementoneormoreofthefollowinginterfaces:javax.
servlet.
ServletContextAttributeListenerjavax.
servlet.
ServletRequestListenerjavax.
servlet.
ServletRequestAttributeListenerjavax.
servlet.
http.
HttpSessionListenerjavax.
servlet.
http.
HttpSessionAttributeListenerjavax.
servlet.
http.
HttpSessionIdListenerIftheServletContextwaspassedtotheServletContainerInitializer'sonStartupmethod,thenthegivenlistenerclassMAYalsoimplementjavax.
servlet.
ServletContextListenerinadditiontotheinterfaceslistedabove.
Ifthegivenlistenerclassimplementsalistenerinterfacewhoseinvocationordercorrespondstothedeclarationorder,thatis,ifitimplementsjavax.
servlet.
ServletRequestListener,javax.
servlet.
ServletContextListenerorjavax.
servlet.
http.
HttpSessionListener,thenthenewlistenerwillbeaddedtotheendoftheorderedlistoflistenersofthatinterface.
4.
4.
3.
4voidcreateListener(Classclazz)ThismethodinstantiatesthegivenEventListenerclass.
ThespecifiedEventListenerclassMUSTimplementatleastoneofthefollowinginterfaces:javax.
servlet.
ServletContextAttributeListenerjavax.
servlet.
ServletRequestListenerjavax.
servlet.
ServletRequestAttributeListenerjavax.
servlet.
http.
HttpSessionListener40JavaServletSpecificationjavax.
servlet.
http.
HttpSessionAttributeListenerjavax.
servlet.
http.
HttpSessionIdListenerThismethodMUSTsupportallannotationsapplicabletotheabovelistenerinterfacesasdefinedbythisspecification.
ThereturnedEventListenerinstancemaybefurthercustomizedbeforeitisregisteredwiththeServletContextviaacalltoaddListener(Tt).
ThegivenEventListenerclassMUSTdefineazeroargumentconstructor,whichisusedtoinstantiateit.
4.
4.
3.
5AnnotationprocessingrequirementsforprogrammaticallyaddedServlets,FiltersandListenersWhenusingtheprogrammaticAPItoaddaservletorcreateaservlet,apartfromtheaddServletthattakesaninstance,thefollowingannotationsmustbeintrospectedintheclassinquestionandthemetadatadefinedinitMUSTbeusedunlessitisoverriddenbycallstotheAPIintheServletRegistration.
Dynamic/ServletRegistration.
@ServletSecurity,@RunAs,@DeclareRoles,@MultipartConfig.
ForFiltersandListenersnoannotationsneedtobeintrospected.
Resourceinjectiononallcomponents(Servlets,FiltersandListeners)addedprogrammaticallyorcreatedprogrammatically,otherthantheonesaddedviathemethodsthattakesaninstance,willonlybesupportedwhenthecomponentisaCDIManagedBean.
FordetailspleaserefertoSection15.
5.
15,"ContextsandDependencyInjectionforJavaEErequirements"onpage15-197.
4.
5ContextAttributesAservletcanbindanobjectattributeintothecontextbyname.
AnyattributeboundintoacontextisavailabletoanyotherservletthatispartofthesameWebapplication.
ThefollowingmethodsofServletContextinterfaceallowaccesstothisfunctionality:setAttributegetAttributegetAttributeNamesremoveAttributeChapter4ServletContext414.
5.
1ContextAttributesinaDistributedContainerContextattributesarelocaltotheJVMinwhichtheywerecreated.
ThispreventsServletContextattributesfrombeingasharedmemorystoreinadistributedcontainer.
Wheninformationneedstobesharedbetweenservletsrunninginadistributedenvironment,theinformationshouldbeplacedintoasession(SeeChapter7,"Sessions"),storedinadatabase,orsetinanEnterpriseJavaBeanscomponent.
4.
6ResourcesTheServletContextinterfaceprovidesdirectaccessonlytothehierarchyofstaticcontentdocumentsthatarepartoftheWebapplication,includingHTML,GIF,andJPEGfiles,viathefollowingmethodsoftheServletContextinterface:getResourcegetResourceAsStreamThegetResourceandgetResourceAsStreammethodstakeaStringwithaleading"/"asanargumentthatgivesthepathoftheresourcerelativetotherootofthecontextorrelativetotheMETA-INF/resourcesdirectoryofaJARfileinsidethewebapplication'sWEB-INF/libdirectory.
ThesemethodswillfirstsearchtherootofthewebapplicationcontextfortherequestedresourcebeforelookingatanyoftheJARfilesintheWEB-INF/libdirectory.
TheorderinwhichtheJARfilesintheWEB-INF/libdirectoryarescannedisundefined.
Thishierarchyofdocumentsmayexistintheserver'sfilesystem,inaWebapplicationarchivefile,onaremoteserver,oratsomeotherlocation.
Thesemethodsarenotusedtoobtaindynamiccontent.
Forexample,inacontainersupportingtheJavaServerPagesspecification1,amethodcalloftheformgetResource("/index.
jsp")wouldreturntheJSPsourcecodeandnottheprocessedoutput.
SeeChapter9,"DispatchingRequests"formoreinformationaboutaccessingdynamiccontent.
ThefulllistingoftheresourcesintheWebapplicationcanbeaccessedusingthegetResourcePaths(Stringpath)method.
ThefulldetailsonthesemanticsofthismethodmaybefoundintheAPIdocumentationinthisspecification.
1.
TheJavaServerPagesspecificationcanbefoundathttp://java.
sun.
com/products/jsp42JavaServletSpecification4.
7MultipleHostsandServletContextsWebserversmaysupportmultiplelogicalhostssharingoneIPaddressonaserver.
Thiscapabilityissometimesreferredtoas"virtualhosting".
Inthiscase,eachlogicalhostmusthaveitsownservletcontextorsetofservletcontexts.
Servletcontextscannotbesharedacrossvirtualhosts.
ThegetVirtualServerNamemethodofServletContextinterfaceallowsaccesstotheconfigurationnameofthelogicalhostonwhichtheServletContextisdeployed.
Servletcontainersmaysupportmultiplelogicalhosts.
Thismethodmustreturnthesamenameforalltheservletcontextsdeployedonalogicalhost,andthenamereturnedbythismethodmustbedistinct,stableperlogicalhost,andsuitableforuseinassociatingserverconfigurationinformationwiththelogicalhost.
4.
8ReloadingConsiderationsAlthoughaContainerProviderimplementationofaclassreloadingschemeforeaseofdevelopmentisnotrequired,anysuchimplementationmustensurethatallservlets,andclassesthattheymayuse2,areloadedinthescopeofasingleclassloader.
ThisrequirementisneededtoguaranteethattheapplicationwillbehaveasexpectedbytheDeveloper.
Asadevelopmentaid,thefullsemanticsofnotificationtosessionbindinglistenersshouldbesupportedbycontainersforuseinthemonitoringofsessionterminationuponclassreloading.
Previousgenerationsofcontainerscreatednewclassloaderstoloadaservlet,distinctfromclassloadersusedtoloadotherservletsorclassesusedintheservletcontext.
Thiscouldcauseobjectreferenceswithinaservletcontexttopointatunexpectedclassesorobjects,andcauseunexpectedbehavior.
Therequirementisneededtopreventproblemscausedbydemandgenerationofnewclassloaders.
4.
8.
1TemporaryWorkingDirectoriesAtemporarystoragedirectoryisrequiredforeachservletcontext.
Servletcontainersmustprovideaprivatetemporarydirectoryforeachservletcontext,andmakeitavailableviathejavax.
servlet.
context.
tempdircontextattribute.
Theobjectsassociatedwiththeattributemustbeoftypejava.
io.
File.
2.
Anexceptionissystemclassesthattheservletmayuseinadifferentclassloader.
Chapter4ServletContext43Therequirementrecognizesacommonconvenienceprovidedinmanyservletengineimplementations.
Thecontainerisnotrequiredtomaintainthecontentsofthetemporarydirectorywhentheservletcontainerrestarts,butisrequiredtoensurethatthecontentsofthetemporarydirectoryofoneservletcontextisnotvisibletotheservletcontextsofotherWebapplicationsrunningontheservletcontainer.
44JavaServletSpecification45CHAPTER5TheResponseTheresponseobjectencapsulatesallinformationtobereturnedfromtheservertotheclient.
IntheHTTPprotocol,thisinformationistransmittedfromtheservertotheclienteitherbyHTTPheadersorthemessagebodyoftherequest.
5.
1BufferingAservletcontainerisallowed,butnotrequired,tobufferoutputgoingtotheclientforefficiencypurposes.
Typicallyserversthatdobufferingmakeitthedefault,butallowservletstospecifybufferingparameters.
ThefollowingmethodsintheServletResponseinterfaceallowaservlettoaccessandsetbufferinginformation:getBufferSizesetBufferSizeisCommittedresetresetBufferflushBufferThesemethodsareprovidedontheServletResponseinterfacetoallowbufferingoperationstobeperformedwhethertheservletisusingaServletOutputStreamoraWriter.
ThegetBufferSizemethodreturnsthesizeoftheunderlyingbufferbeingused.
Ifnobufferingisbeingused,thismethodmustreturntheintvalueof0(zero).
TheservletcanrequestapreferredbuffersizebyusingthesetBufferSizemethod.
Thebufferassignedisnotrequiredtobethesizerequestedbytheservlet,butmustbeatleastaslargeasthesizerequested.
Thisallowsthecontainertoreuseasetoffixedsizebuffers,providingalargerbufferthanrequestedifappropriate.
The46JavaServletSpecificationmethodmustbecalledbeforeanycontentiswrittenusingaServletOutputStreamorWriter.
Ifanycontenthasbeenwrittenortheresponseobjecthasbeencommitted,thismethodmustthrowanIllegalStateException.
TheisCommittedmethodreturnsabooleanvalueindicatingwhetheranyresponsebyteshavebeenreturnedtotheclient.
TheflushBuffermethodforcescontentinthebuffertobewrittentotheclient.
Theresetmethodclearsdatainthebufferwhentheresponseisnotcommitted.
Headers,statuscodesandthestateofcallinggetWriterorgetOutputStreamsetbytheservletpriortotheresetcallmustbeclearedaswell.
TheresetBuffermethodclearscontentinthebufferiftheresponseisnotcommittedwithoutclearingtheheadersandstatuscode.
IftheresponseiscommittedandtheresetorresetBuffermethodiscalled,anIllegalStateExceptionmustbethrown.
Theresponseanditsassociatedbufferwillbeunchanged.
Whenusingabuffer,thecontainermustimmediatelyflushthecontentsofafilledbuffertotheclient.
Ifthisisthefirstdatathatissenttotheclient,theresponseisconsideredtobecommitted.
5.
2HeadersAservletcansetheadersofanHTTPresponseviathefollowingmethodsoftheHttpServletResponseinterface:setHeaderaddHeaderThesetHeadermethodsetsaheaderwithagivennameandvalue.
Apreviousheaderisreplacedbythenewheader.
Whereasetofheadervaluesexistforthename,thevaluesareclearedandreplacedwiththenewvalue.
TheaddHeadermethodaddsaheadervaluetothesetwithagivenname.
Iftherearenoheadersalreadyassociatedwiththename,anewsetiscreated.
HeadersmaycontaindatathatrepresentsanintoraDateobject.
ThefollowingconveniencemethodsoftheHttpServletResponseinterfaceallowaservlettosetaheaderusingthecorrectformattingfortheappropriatedatatype:setIntHeadersetDateHeaderaddIntHeaderaddDateHeaderChapter5TheResponse47Tobesuccessfullytransmittedbacktotheclient,headersmustbesetbeforetheresponseiscommitted.
Headerssetaftertheresponseiscommittedwillbeignoredbytheservletcontainer.
ServletprogrammersareresponsibleforensuringthattheContent-Typeheaderisappropriatelysetintheresponseobjectforthecontenttheservletisgenerating.
TheHTTP1.
1specificationdoesnotrequirethatthisheaderbesetinanHTTPresponse.
Servletcontainersmustnotsetadefaultcontenttypewhentheservletprogrammerdoesnotsetthetype.
ItisrecommendedthatcontainersusetheX-Powered-ByHTTPheadertopublishitsimplementationinformation.
Thefieldvalueshouldconsistofoneormoreimplementationtypes,suchas"Servlet/3.
1".
Optionally,thesupplementaryinformationofthecontainerandtheunderlyingJavaplatformcanbeaddedaftertheimplementationtypewithinparentheses.
Thecontainershouldbeconfigurabletosuppressthisheader.
Here'stheexamplesofthisheader.
X-Powered-By:Servlet/3.
1X-Powered-By:Servlet/3.
1JSP/2.
2(GlassFishv3JRE/1.
6.
0)5.
3NonBlockingIONon-blockingIOonlyworkswithasyncrequestprocessinginServletsandFilters(asdefinedinSection2.
3.
3.
3,"Asynchronousprocessing"onpage2-10),andupgradeprocessing(asdefinedinSection2.
3.
3.
5,"UpgradeProcessing"onpage2-20).
Otherwise,anIllegalStateExceptionmustbethrownwhenServletInputStream.
setReadListenerorServletOutputStream.
setWriteListenerisinvoked.
Tosupportnon-blockingwritesintheWebcontainer,inadditiontothechangesmadeintheServletRequestasdescribedinSection3.
7,"NonBlockingIO"onpage3-28,thefollowingchangeshavebeenmadetohandleresponserelatedclasses/interfaces.
TheWriteListenerprovidesthefollowingcallbackmethodswhichthecontainerinvokesappropriately.
WriteListenervoidonWritePossible().
WhenaWriteListenerisregisteredwiththeServletOutputStream,thismethodwillbeinvokedbythecontainerthefirsttimewhenitispossibletowritedata.
ThecontainerwillsubsequentlyinvoketheonWritePossiblemethodifandonlyifisReadymethodonServletOutputStream,describedbelow,returnsfalse.
onError(Throwablet).
Invokedwhenanerroroccursprocessingtheresponse.
48JavaServletSpecificationAlongwiththeWriteListener,thefollowingmethodshavebeenaddedtoServletOutputStreamclasstoallowthedevelopertocheckwiththeruntimewhetherornotitispossibletowritethedatatobesenttotheclient.
ServletOutputStreambooleanisReady().
ThismethodreturnstrueifawritetotheServletOutputStreamwillsucceed,otherwiseitwillreturnfalse.
Ifthismethodreturnstrue,awriteoperationcanbeperformedontheServletOutputStream.
IfnofurtherdatacanbewrittentotheServletOutputStream.
thenthismethodwillreturnfalsetilltheunderlyingdataisflushedatwhichpointthecontainerwillinvoketheonWritePossiblemethodoftheWriteListener.
Asubsequentcalltothismethodwillreturntrue.
voidsetWriteListener(WriteListenerlistener).
AssociatestheWriteListenerwiththisServletOutputStream.
forthecontainertoinvokethecallbackmethodsontheWriteListenerwhenitispossibletowritedata.
RegisteringaWriteListenerwillstartnon-blockingIO.
ItisillegaltoswitchtothetraditionalblockingIOatthatpoint.
TheServletcontainermustaccessmethodsinWriteListenerinathreadsafemanner.
5.
4ConvenienceMethodsThefollowingconveniencemethodsexistintheHttpServletResponseinterface:sendRedirectsendErrorThesendRedirectmethodwillsettheappropriateheadersandcontentbodytoredirecttheclienttoadifferentURL.
ItislegaltocallthismethodwitharelativeURLpath,howevertheunderlyingcontainermusttranslatetherelativepathtoafullyqualifiedURLfortransmissionbacktotheclient.
IfapartialURLisgivenand,forwhateverreason,cannotbeconvertedintoavalidURL,thenthismethodmustthrowanIllegalArgumentException.
ThesendErrormethodwillsettheappropriateheadersandcontentbodyforanerrormessagetoreturntotheclient.
AnoptionalStringargumentcanbeprovidedtothesendErrormethodwhichcanbeusedinthecontentbodyoftheerror.
Thesemethodswillhavethesideeffectofcommittingtheresponse,ifithasnotalreadybeencommitted,andterminatingit.
Nofurtheroutputtotheclientshouldbemadebytheservletafterthesemethodsarecalled.
Ifdataiswrittentotheresponseafterthesemethodsarecalled,thedataisignored.
Chapter5TheResponse49Ifdatahasbeenwrittentotheresponsebuffer,butnotreturnedtotheclient(i.
e.
theresponseisnotcommitted),thedataintheresponsebuffermustbeclearedandreplacedwiththedatasetbythesemethods.
Iftheresponseiscommitted,thesemethodsmustthrowanIllegalStateException.
5.
5InternationalizationServletsshouldsetthelocaleandthecharacterencodingofaresponse.
ThelocaleissetusingtheServletResponse.
setLocalemethod.
Themethodcanbecalledrepeatedly;butcallsmadeaftertheresponseiscommittedhavenoeffect.
Iftheservletdoesnotsetthelocalebeforethepageiscommitted,thecontainer'sdefaultlocaleisusedtodeterminetheresponse'slocale,butnospecificationismadeforthecommunicationwithaclient,suchasContent-LanguageheaderinthecaseofHTTP.
Iftheelementdoesnotexistordoesnotprovideamapping,setLocaleusesacontainerdependentmapping.
ThesetCharacterEncoding,setContentType,andsetLocalemethodscanbecalledrepeatedlytochangethecharacterencoding.
Callsmadeaftertheservletresponse'sgetWritermethodhasbeencalledoraftertheresponseiscommittedhavenoeffectonthecharacterencoding.
CallstosetContentTypesetthecharacterencodingonlyifthegivencontenttypestringprovidesavalueforthecharsetattribute.
CallstosetLocalesetthecharacterencodingonlyifneithersetCharacterEncodingnorsetContentTypehassetthecharacterencodingbefore.
IftheservletdoesnotspecifyacharacterencodingbeforethegetWritermethodoftheServletResponseinterfaceiscalledortheresponseiscommitted,thedefaultISO-8859-1isused.
Containersmustcommunicatethelocaleandthecharacterencodingusedfortheservletresponse'swritertotheclientiftheprotocolinuseprovidesawayfordoingso.
InthecaseofHTTP,thelocaleiscommunicatedviatheContent-Languageheader,thecharacterencodingaspartoftheContent-Typeheaderfortextmediatypes.
NotethatthecharacterencodingcannotbecommunicatedviaHTTPheadersiftheservletdoesnotspecifyacontenttype;however,itisstillusedtoencodetextwrittenviatheservletresponse'swriter.
jaShift_JIS50JavaServletSpecification5.
6ClosureofResponseObjectWhenaresponseisclosed,thecontainermustimmediatelyflushallremainingcontentintheresponsebuffertotheclient.
Thefollowingeventsindicatethattheservlethassatisfiedtherequestandthattheresponseobjectistobeclosed:Theterminationoftheservicemethodoftheservlet.
TheamountofcontentspecifiedinthesetContentLengthorsetContentLengthLongmethodoftheresponsehasbeengreaterthanzeroandhasbeenwrittentotheresponse.
ThesendErrormethodiscalled.
ThesendRedirectmethodiscalled.
ThecompletemethodonAsyncContextiscalled.
5.
7LifetimeoftheResponseObjectEachresponseobjectisvalidonlywithinthescopeofaservlet'sservicemethod,orwithinthescopeofafilter'sdoFiltermethod,unlesstheassociatedrequestobjecthasasynchronousprocessingenabledforthecomponent.
Ifasynchronousprocessingontheassociatedrequestisstarted,thentherequestobjectremainsvaliduntilcompletemethodonAsyncContextiscalled.
Containerscommonlyrecycleresponseobjectsinordertoavoidtheperformanceoverheadofresponseobjectcreation.
ThedevelopermustbeawarethatmaintainingreferencestoresponseobjectsforwhichstartAsynconthecorrespondingrequesthasnotbeencalled,outsidethescopedescribedabovemayleadtonon-deterministicbehavior.
51CHAPTER6FilteringFiltersareJavacomponentsthatallowontheflytransformationsofpayloadandheaderinformationinboththerequestintoaresourceandtheresponsefromaresourceThischapterdescribestheJavaServletv.
3.
0APIclassesandmethodsthatprovidealightweightframeworkforfilteringactiveandstaticcontent.
ItdescribeshowfiltersareconfiguredinaWebapplication,andconventionsandsemanticsfortheirimplementation.
APIdocumentationforservletfiltersisprovidedonline.
TheconfigurationsyntaxforfiltersisgivenbythedeploymentdescriptorschemainChapter14,"DeploymentDescriptor".
Thereadershouldusethesesourcesasreferenceswhenreadingthischapter.
6.
1WhatisafilterAfilterisareusablepieceofcodethatcantransformthecontentofHTTPrequests,responses,andheaderinformation.
Filtersdonotgenerallycreatearesponseorrespondtoarequestasservletsdo,rathertheymodifyoradapttherequestsforaresource,andmodifyoradaptresponsesfromaresource.
Filterscanactondynamicorstaticcontent.
Forthepurposesofthischapter,dynamicandstaticcontentarereferredtoasWebresources.
Amongthetypesoffunctionalityavailabletothedeveloperneedingtousefiltersarethefollowing:Theaccessingofaresourcebeforearequesttoitisinvoked.
Theprocessingoftherequestforaresourcebeforeitisinvoked.
Themodificationofrequestheadersanddatabywrappingtherequestincustomizedversionsoftherequestobject.
52JavaServletSpecificationThemodificationofresponseheadersandresponsedatabyprovidingcustomizedversionsoftheresponseobject.
Theinterceptionofaninvocationofaresourceafteritscall.
Actionsonaservlet,ongroupsofservlets,orstaticcontentbyzero,one,ormorefiltersinaspecifiableorder.
6.
1.
1ExamplesofFilteringComponentsAuthenticationfiltersLoggingandauditingfiltersImageconversionfiltersDatacompressionfiltersEncryptionfiltersTokenizingfiltersFiltersthattriggerresourceaccesseventsXSL/TfiltersthattransformXMLcontentMIME-typechainfiltersCachingfilters6.
2MainConceptsThemainconceptsofthisfilteringmodelaredescribedinthissection.
Theapplicationdevelopercreatesafilterbyimplementingthejavax.
servlet.
Filterinterfaceandprovidingapublicconstructortakingnoarguments.
TheclassispackagedintheWebArchivealongwiththestaticcontentandservletsthatmakeuptheWebapplication.
Afilterisdeclaredusingtheelementinthedeploymentdescriptor.
Afilterorcollectionoffilterscanbeconfiguredforinvocationbydefiningelementsinthedeploymentdescriptor.
Thisisdonebymappingfilterstoaparticularservletbytheservlet'slogicalname,ormappingtoagroupofservletsandstaticcontentresourcesbymappingafiltertoaURLpattern.
6.
2.
1FilterLifecycleAfterdeploymentoftheWebapplication,andbeforearequestcausesthecontainertoaccessaWebresource,thecontainermustlocatethelistoffiltersthatmustbeappliedtotheWebresourceasdescribedbelow.
Thecontainermustensurethatithasinstantiatedafilteroftheappropriateclassforeachfilterinthelist,andcalleditsinit(FilterConfigconfig)method.
ThefiltermaythrowanexceptiontoChapter6Filtering53indicatethatitcannotfunctionproperly.
IftheexceptionisoftypeUnavailableException,thecontainermayexaminetheisPermanentattributeoftheexceptionandmaychoosetoretrythefilteratsomelatertime.
OnlyoneinstanceperdeclarationinthedeploymentdescriptorisinstantiatedperJVMofthecontainer.
Thecontainerprovidesthefilterconfigasdeclaredinthefilter'sdeploymentdescriptor,thereferencetotheServletContextfortheWebapplication,andthesetofinitializationparameters.
Whenthecontainerreceivesanincomingrequest,ittakesthefirstfilterinstanceinthelistandcallsitsdoFiltermethod,passingintheServletRequestandServletResponse,andareferencetotheFilterChainobjectitwilluse.
ThedoFiltermethodofafilterwilltypicallybeimplementedfollowingthisorsomesubsetofthefollowingpattern:1.
Themethodexaminestherequest'sheaders.
2.
ThemethodmaywraptherequestobjectwithacustomizedimplementationofServletRequestorHttpServletRequestinordertomodifyrequestheadersordata.
3.
ThemethodmaywraptheresponseobjectpassedintoitsdoFiltermethodwithacustomizedimplementationofServletResponseorHttpServletResponsetomodifyresponseheadersordata.
4.
Thefiltermayinvokethenextentityinthefilterchain.
Thenextentitymaybeanotherfilter,orifthefiltermakingtheinvocationisthelastfilterconfiguredinthedeploymentdescriptorforthischain,thenextentityisthetargetWebresource.
TheinvocationofthenextentityiseffectedbycallingthedoFiltermethodontheFilterChainobject,andpassingintherequestandresponsewithwhichitwascalledorpassinginwrappedversionsitmayhavecreated.
Thefilterchain'simplementationofthedoFiltermethod,providedbythecontainer,mustlocatethenextentityinthefilterchainandinvokeitsdoFiltermethod,passingintheappropriaterequestandresponseobjects.
Alternatively,thefilterchaincanblocktherequestbynotmakingthecalltoinvokethenextentity,leavingthefilterresponsibleforfillingouttheresponseobject.
Theservicemethodisrequiredtoruninthesamethreadasallfiltersthatapplytotheservlet.
5.
Afterinvocationofthenextfilterinthechain,thefiltermayexamineresponseheaders.
6.
Alternatively,thefiltermayhavethrownanexceptiontoindicateanerrorinprocessing.
IfthefilterthrowsanUnavailableExceptionduringitsdoFilterprocessing,thecontainermustnotattemptcontinuedprocessingdownthefilterchain.
Itmaychoosetoretrythewholechainatalatertimeiftheexceptionisnotmarkedpermanent.
54JavaServletSpecification7.
Whenthelastfilterinthechainhasbeeninvoked,thenextentityaccessedisthetargetservletorresourceattheendofthechain.
8.
Beforeafilterinstancecanberemovedfromservicebythecontainer,thecontainermustfirstcallthedestroymethodonthefiltertoenablethefiltertoreleaseanyresourcesandperformothercleanupoperations.
6.
2.
2WrappingRequestsandResponsesCentraltothenotionoffilteringistheconceptofwrappingarequestorresponseinorderthatitcanoverridebehaviortoperformafilteringtask.
Inthismodel,thedevelopernotonlyhastheabilitytooverrideexistingmethodsontherequestandresponseobjects,buttoprovidenewAPIsuitedtoaparticularfilteringtasktoafilterortargetwebresourcedownthechain.
Forexample,thedevelopermaywishtoextendtheresponseobjectwithhigherleveloutputobjectsthattheoutputstreamorthewriter,suchasAPIthatallowsDOMobjectstobewrittenbacktotheclient.
Inordertosupportthisstyleoffilterthecontainermustsupportthefollowingrequirement.
WhenafilterinvokesthedoFiltermethodonthecontainer'sfilterchainimplementation,thecontainermustensurethattherequestandresponseobjectthatitpassestothenextentityinthefilterchain,ortothetargetwebresourceifthefilterwasthelastinthechain,isthesameobjectthatwaspassedintothedoFiltermethodbythecallingfilter.
ThesamerequirementofwrapperobjectidentityappliestothecallsfromaservletorafiltertoRequestDispatcher.
forwardorRequestDispatcher.
include,whenthecallerwrapstherequestorresponseobjects.
Inthiscase,therequestandresponseobjectsseenbythecalledservletmustbethesamewrapperobjectsthatwerepassedinbythecallingservletorfilter.
6.
2.
3FilterEnvironmentAsetofinitializationparameterscanbeassociatedwithafilterusingtheelementinthedeploymentdescriptor.
ThenamesandvaluesoftheseparametersareavailabletothefilteratruntimeviathegetInitParameterandgetInitParameterNamesmethodsonthefilter'sFilterConfigobject.
Additionally,theFilterConfigaffordsaccesstotheServletContextoftheWebapplicationfortheloadingofresources,forloggingfunctionality,andforstorageofstateintheServletContext'sattributelist.
AFilterandthetargetservletorresourceattheendofthefilterchainmustexecuteinthesameinvocationthread.
Chapter6Filtering556.
2.
4ConfigurationofFiltersinaWebApplicationAfilterisdefinedeitherviathe@WebFilterannotationasdefinedinSection8.
1.
2,"@WebFilter"onpage8-69ofthespecificationorinthedeploymentdescriptorusingtheelement.
Inthiselement,theprogrammerdeclaresthefollowing:filter-name:usedtomapthefiltertoaservletorURLfilter-class:usedbythecontainertoidentifythefiltertypeinit-params:initializationparametersforafilterOptionally,theprogrammercanspecifyicons,atextualdescription,andadisplaynamefortoolmanipulation.
ThecontainermustinstantiateexactlyoneinstanceoftheJavaclassdefiningthefilterperfilterdeclarationinthedeploymentdescriptor.
Hence,twoinstancesofthesamefilterclasswillbeinstantiatedbythecontainerifthedevelopermakestwofilterdeclarationsforthesamefilterclass.
Hereisanexampleofafilterdeclaration:Onceafilterhasbeendeclaredinthedeploymentdescriptor,theassemblerusestheelementtodefineservletsandstaticresourcesintheWebapplicationtowhichthefilteristobeapplied.
Filterscanbeassociatedwithaservletusingtheelement.
Forexample,thefollowingcodeexamplemapstheImageFilterfiltertotheImageServletservlet:Filterscanbeassociatedwithgroupsofservletsandstaticcontentusingthestyleoffiltermapping:HeretheLoggingFilterisappliedtoalltheservletsandstaticcontentpagesintheWebapplication,becauseeveryrequestURImatchesthe'/*'URLpattern.
ImageFiltercom.
acme.
ImageServletImageFilterImageServletLoggingFilter/*56JavaServletSpecificationWhenprocessingaelementusingthestyle,thecontainermustdeterminewhetherthematchestherequestURIusingthepathmappingrulesdefinedinChapter12,"MappingRequeststoServlets".
TheorderthecontainerusesinbuildingthechainoffilterstobeappliedforaparticularrequestURIisasfollows:1.
First,thematchingfiltermappingsinthesameorderthattheseelementsappearinthedeploymentdescriptor.
2.
Next,thematchingfiltermappingsinthesameorderthattheseelementsappearinthedeploymentdescriptor.
Ifafiltermappingcontainsbothand,thecontainermustexpandthefiltermappingintomultiplefiltermappings(oneforeachand),preservingtheorderoftheandelements.
Forexample,thefollowingfiltermapping:MultipeMappingsFilter/foo/*Servlet1Servlet2/bar/*Chapter6Filtering57isequivalentto:Therequirementabouttheorderofthefilterchainmeansthatthecontainer,whenreceivinganincomingrequest,processestherequestasfollows:IdentifiesthetargetWebresourceaccordingtotherulesof"SpecificationofMappings"onpage122.
IftherearefiltersmatchedbyservletnameandtheWebresourcehasa,thecontainerbuildsthechainoffiltersmatchingintheorderdeclaredinthedeploymentdescriptor.
ThelastfilterinthischaincorrespondstothelastmatchingfilterandisthefilterthatinvokesthetargetWebresource.
IftherearefiltersusingmatchingandthematchestherequestURIaccordingtotherulesofSection12.
2,"SpecificationofMappings",thecontainerbuildsthechainofmatchedfiltersinthesameorderasdeclaredinthedeploymentdescriptor.
ThelastfilterinthischainisthelastmatchingfilterinthedeploymentdescriptorforthisrequestURI.
Thelastfilterinthischainisthefilterthatinvokesthefirstfilterinthematchingchain,orinvokesthetargetWebresourceiftherearenone.
ItisexpectedthathighperformanceWebcontainerswillcachefilterchainssothattheydonotneedtocomputethemonaper-requestbasis.
MultipeMappingsFilter/foo/*MultipeMappingsFilterServlet1MultipeMappingsFilterServlet2MultipeMappingsFilter/bar/*58JavaServletSpecification6.
2.
5FiltersandtheRequestDispatcherNewsinceversion2.
4oftheJavaServletspecificationistheabilitytoconfigurefilterstobeinvokedunderrequestdispatcherforward()andinclude()calls.
Byusingthenewelementinthedeploymentdescriptor,thedevelopercanindicateforafilter-mappingwhetherhewouldlikethefiltertobeappliedtorequestswhen:1.
Therequestcomesdirectlyfromtheclient.
ThisisindicatedbyaelementwithvalueREQUEST,orbytheabsenceofanyelements.
2.
TherequestisbeingprocessedunderarequestdispatcherrepresentingtheWebcomponentmatchingtheorusingaforward()call.
ThisisindicatedbyaelementwithvalueFORWARD.
3.
TherequestisbeingprocessedunderarequestdispatcherrepresentingtheWebcomponentmatchingtheorusinganinclude()call.
ThisisindicatedbyaelementwithvalueINCLUDE.
4.
Therequestisbeingprocessedwiththeerrorpagemechanismspecifiedin"ErrorHandling"onpage108toanerrorresourcematchingthe.
ThisisindicatedbyaelementwiththevalueERROR.
5.
Therequestisbeingprocessedwiththeasynccontextdispatchmechanismspecifiedin"Asynchronousprocessing"onpage10toawebcomponentusingadispatchcall.
ThisisindicatedbyaelementwiththevalueASYNC.
6.
Oranycombinationof1,2,3,4or5above.
Forexample:LoggingFilter/products/*Chapter6Filtering59wouldresultintheLoggingFilterbeinginvokedbyclientrequestsstarting/products/.
.
.
butnotunderneatharequestdispatchercallwheretherequestdispatcherhaspathcommencing/products/.
.
.
.
TheLoggingFilterwouldbeinvokedbothontheinitialdispatchoftherequestandonresumedrequest.
Thefollowingcode:wouldresultintheLoggingFilternotbeinginvokedbyclientrequeststotheProductServlet,norunderneatharequestdispatcherforward()calltotheProductServlet,butwouldbeinvokedunderneatharequestdispatcherinclude()callwheretherequestdispatcherhasanamecommencingProductServlet.
Thefollowingcode:wouldresultintheLoggingFilterbeinginvokedbyclientrequestsstarting/products/.
.
.
andunderneatharequestdispatcherforward()callwheretherequestdispatcherhaspathcommencing/products/.
.
.
.
Finally,thefollowingcodeusesthespecialservletname'*':ThiscodewouldresultintheAllDispatchFilterbeinginvokedonrequestdispatcherforward()callsforallrequestdispatchersobtainedbynameorbypath.
LoggingFilterProductServletINCLUDELoggingFilter/products/*FORWARDREQUESTAllDispatchFilter*FORWARD60JavaServletSpecification61CHAPTER7SessionsTheHypertextTransferProtocol(HTTP)isbydesignastatelessprotocol.
TobuildeffectiveWebapplications,itisimperativethatrequestsfromaparticularclientbeassociatedwitheachother.
Manystrategiesforsessiontrackinghaveevolvedovertime,butallaredifficultortroublesomefortheprogrammertousedirectly.
ThisspecificationdefinesasimpleHttpSessioninterfacethatallowsaservletcontainertouseanyofseveralapproachestotrackauser'ssessionwithoutinvolvingtheApplicationDeveloperinthenuancesofanyoneapproach.
7.
1SessionTrackingMechanismsThefollowingsectionsdescribeapproachestotrackingauser'ssessions7.
1.
1CookiesSessiontrackingthroughHTTPcookiesisthemostusedsessiontrackingmechanismandisrequiredtobesupportedbyallservletcontainers.
Thecontainersendsacookietotheclient.
Theclientwillthenreturnthecookieoneachsubsequentrequesttotheserver,unambiguouslyassociatingtherequestwithasession.
ThestandardnameofthesessiontrackingcookiemustbeJSESSIONID,whichmustbesupportedbyall3.
0compliantcontainers.
Containersmayallowthenameofthesessiontrackingcookietobecustomizedthroughcontainerspecificconfiguration.
AllservletcontainersMUSTprovideanabilitytoconfigurewhetherornotthecontainermarksthesessiontrackingcookieasHttpOnly.
Theestablishedconfigurationmustapplytoallcontextsforwhichacontextspecificconfigurationhasnotbeenestablished(seeSessionCookieConfigjavadocformoredetails).
62JavaServletSpecificationIfawebapplicationconfiguresacustomnameforitssessiontrackingcookies,thesamecustomnamewillalsobeusedasthenameoftheURIparameterifthesessionidisencodedintheURL(providedthatURLrewritinghasbeenenabled).
7.
1.
2SSLSessionsSecureSocketsLayer,theencryptiontechnologyusedintheHTTPSprotocol,hasabuilt-inmechanismallowingmultiplerequestsfromaclienttobeunambiguouslyidentifiedasbeingpartofasession.
Aservletcontainercaneasilyusethisdatatodefineasession.
7.
1.
3URLRewritingURLrewritingisthelowestcommondenominatorofsessiontracking.
Whenaclientwillnotacceptacookie,URLrewritingmaybeusedbytheserverasthebasisforsessiontracking.
URLrewritinginvolvesaddingdata,asessionID,totheURLpaththatisinterpretedbythecontainertoassociatetherequestwithasession.
ThesessionIDmustbeencodedasapathparameterintheURLstring.
Thenameoftheparametermustbejsessionid.
HereisanexampleofaURLcontainingencodedpathinformation:http://www.
myserver.
com/catalog/index.
html;jsessionid=1234URLrewritingexposessessionidentifiersinlogs,bookmarks,refererheaders,cachedHTML,andtheURLbar.
URLrewritingshouldnotbeusedasasessiontrackingmechanismwherecookiesorSSLsessionsaresupportedandsuitable.
7.
1.
4SessionIntegrityWebcontainersmustbeabletosupporttheHTTPsessionwhileservicingHTTPrequestsfromclientsthatdonotsupporttheuseofcookies.
Tofulfillthisrequirement,WebcontainerscommonlysupporttheURLrewritingmechanism.
7.
2CreatingaSessionAsessionisconsidered"new"whenitisonlyaprospectivesessionandhasnotbeenestablished.
BecauseHTTPisarequest-responsebasedprotocol,anHTTPsessionisconsideredtobenewuntilaclient"joins"it.
AclientjoinsasessionwhensessionChapter7Sessions63trackinginformationhasbeenreturnedtotheserverindicatingthatasessionhasbeenestablished.
Untiltheclientjoinsasession,itcannotbeassumedthatthenextrequestfromtheclientwillberecognizedaspartofasession.
Thesessionisconsideredtobe"new"ifeitherofthefollowingistrue:TheclientdoesnotyetknowaboutthesessionTheclientchoosesnottojoinasession.
Theseconditionsdefinethesituationwheretheservletcontainerhasnomechanismbywhichtoassociatearequestwithapreviousrequest.
AServletDevelopermustdesignhisapplicationtohandleasituationwhereaclienthasnot,cannot,orwillnotjoinasession.
Associatedwitheachsession,thereisastringcontainingauniqueidentifier,whichisreferredtoasthesessionid.
Thevalueofthesessionidcanbeobtainedbycallingjavax.
servlet.
http.
HttpSession.
getId()andcanbechangedaftercreationbyinvokingjavax.
servlet.
http.
HttpServletRequest.
changeSessionId().
7.
3SessionScopeHttpSessionobjectsmustbescopedattheapplication(orservletcontext)level.
Theunderlyingmechanism,suchasthecookieusedtoestablishthesession,canbethesamefordifferentcontexts,buttheobjectreferenced,includingtheattributesinthatobject,mustneverbesharedbetweencontextsbythecontainer.
Toillustratethisrequirementwithanexample:ifaservletusestheRequestDispatchertocallaservletinanotherWebapplication,anysessionscreatedforandvisibletotheservletbeingcalledmustbedifferentfromthosevisibletothecallingservlet.
Additionally,sessionsofacontextmustberesumablebyrequestsintothatcontextregardlessofwhethertheirassociatedcontextwasbeingaccesseddirectlyorasthetargetofarequestdispatchatthetimethesessionswerecreated.
64JavaServletSpecification7.
4BindingAttributesintoaSessionAservletcanbindanobjectattributeintoanHttpSessionimplementationbyname.
AnyobjectboundintoasessionisavailabletoanyotherservletthatbelongstothesameServletContextandhandlesarequestidentifiedasbeingapartofthesamesession.
Someobjectsmayrequirenotificationwhentheyareplacedinto,orremovedfrom,asession.
ThisinformationcanbeobtainedbyhavingtheobjectimplementtheHttpSessionBindingListenerinterface.
Thisinterfacedefinesthefollowingmethodsthatwillsignalanobjectbeingboundinto,orbeingunboundfrom,asession.
valueBoundvalueUnboundThevalueBoundmethodmustbecalledbeforetheobjectismadeavailableviathegetAttributemethodoftheHttpSessioninterface.
ThevalueUnboundmethodmustbecalledaftertheobjectisnolongeravailableviathegetAttributemethodoftheHttpSessioninterface.
7.
5SessionTimeoutsIntheHTTPprotocol,thereisnoexplicitterminationsignalwhenaclientisnolongeractive.
Thismeansthattheonlymechanismthatcanbeusedtoindicatewhenaclientisnolongeractiveisatimeoutperiod.
ThedefaulttimeoutperiodforsessionsisdefinedbytheservletcontainerandcanbeobtainedviathegetMaxInactiveIntervalmethodoftheHttpSessioninterface.
ThistimeoutcanbechangedbytheDeveloperusingthesetMaxInactiveIntervalmethodoftheHttpSessioninterface.
Thetimeoutperiodsusedbythesemethodsaredefinedinseconds.
Bydefinition,ifthetimeoutperiodforasessionissetto0orlesservalue,thesessionwillneverexpire.
Thesessioninvalidationwillnottakeeffectuntilallservletsusingthatsessionhaveexitedtheservicemethod.
Oncethesessioninvalidationisinitiated,anewrequestmustnotbeabletoseethatsession.
Chapter7Sessions657.
6LastAccessedTimesThegetLastAccessedTimemethodoftheHttpSessioninterfaceallowsaservlettodeterminethelasttimethesessionwasaccessedbeforethecurrentrequest.
Thesessionisconsideredtobeaccessedwhenarequestthatispartofthesessionisfirsthandledbytheservletcontainer.
7.
7ImportantSessionSemantics7.
7.
1ThreadingIssuesMultipleservletsexecutingrequestthreadsmayhaveactiveaccesstothesamesessionobjectatthesametime.
Thecontainermustensurethatmanipulationofinternaldatastructuresrepresentingthesessionattributesisperformedinathreadsafemanner.
TheDeveloperhastheresponsibilityforthreadsafeaccesstotheattributeobjectsthemselves.
ThiswillprotecttheattributecollectioninsidetheHttpSessionobjectfromconcurrentaccess,eliminatingtheopportunityforanapplicationtocausethatcollectiontobecomecorrupted.
7.
7.
2DistributedEnvironmentsWithinanapplicationmarkedasdistributable,allrequeststhatarepartofasessionmustbehandledbyoneJVMatatime.
ThecontainermustbeabletohandleallobjectsplacedintoinstancesoftheHttpSessionclassusingthesetAttributeorputValuemethodsappropriately.
Thefollowingrestrictionsareimposedtomeettheseconditions:ThecontainermustacceptobjectsthatimplementtheSerializableinterface.
ThecontainermaychoosetosupportstorageofotherdesignatedobjectsintheHttpSession,suchasreferencestoEnterpriseJavaBeanscomponentsandtransactions.
Migrationofsessionswillbehandledbycontainer-specificfacilities.
ThedistributedservletcontainermustthrowanIllegalArgumentExceptionforobjectswherethecontainercannotsupportthemechanismnecessaryformigrationofthesessionstoringthem.
66JavaServletSpecificationThedistributedservletcontainermustsupportthemechanismnecessaryformigratingobjectsthatimplementSerializable.
TheserestrictionsmeanthattheDeveloperisensuredthattherearenoadditionalconcurrencyissuesbeyondthoseencounteredinanon-distributedcontainer.
TheContainerProvidercanensurescalabilityandqualityofservicefeatureslikeload-balancingandfailoverbyhavingtheabilitytomoveasessionobject,anditscontents,fromanyactivenodeofthedistributedsystemtoadifferentnodeofthesystem.
Ifdistributedcontainerspersistormigratesessionstoprovidequalityofservicefeatures,theyarenotrestrictedtousingthenativeJVMSerializationmechanismforserializingHttpSessionsandtheirattributes.
DevelopersarenotguaranteedthatcontainerswillcallreadObjectandwriteObjectmethodsonsessionattributesiftheyimplementthem,butareguaranteedthattheSerializableclosureoftheirattributeswillbepreserved.
ContainersmustnotifyanysessionattributesimplementingtheHttpSessionActivationListenerduringmigrationofasession.
Theymustnotifylistenersofpassivationpriortoserializationofasession,andofactivationafterdeserializationofasession.
ApplicationDeveloperswritingdistributedapplicationsshouldbeawarethatsincethecontainermayruninmorethanoneJavavirtualmachine,thedevelopercannotdependonstaticvariablesforstoringanapplicationstate.
Theyshouldstoresuchstatesusinganenterprisebeanoradatabase.
7.
7.
3ClientSemanticsDuetothefactthatcookiesorSSLcertificatesaretypicallycontrolledbytheWebbrowserprocessandarenotassociatedwithanyparticularwindowofthebrowser,requestsfromallwindowsofaclientapplicationtoaservletcontainermightbepartofthesamesession.
Formaximumportability,theDevelopershouldalwaysassumethatallwindowsofaclientareparticipatinginthesamesession.
67CHAPTER8AnnotationsandpluggabilityThischaptertalksabouttheannotationsdefinedinServlet3.
0specificationandtheenhancementstoenablepluggabilityofframeworksandlibrariesforusewithinawebapplication.
8.
1AnnotationsandpluggabilityInawebapplication,classesusingannotationswillhavetheirannotationsprocessedonlyiftheyarelocatedintheWEB-INF/classesdirectory,oriftheyarepackagedinajarfilelocatedinWEB-INF/libwithintheapplication.
Thewebapplicationdeploymentdescriptorcontainsanew"metadata-complete"attributeontheweb-appelement.
The"metadata-complete"attributedefineswhetherthewebdescriptoriscomplete,orwhethertheclassfilesofthejarfileshouldbeexaminedforannotationsandwebfragmentsatdeploymenttime.
If"metadata-complete"issetto"true",thedeploymenttoolMUSTignoreanyservletannotationsthatspecifydeploymentinformationpresentintheclassfilesoftheapplicationandwebfragments.
Ifthemetadata-completeattributeisnotspecifiedorissetto"false",thedeploymenttoolmustexaminetheclassfilesoftheapplicationforannotations,andscanforwebfragments.
FollowingaretheannotationsthatMUSTbesupportedbyaServlet3.
0compliantwebcontainer.
8.
1.
1@WebServletThisannotationisusedtodefineaServletcomponentinawebapplication.
ThisannotationisspecifiedonaclassandcontainsmetadataabouttheServletbeingdeclared.
TheurlPatternsorthevalueattributeontheannotationMUSTbe68JavaServletSpecificationpresent.
Allotherattributesareoptionalwithdefaultsettings(seejavadocsformoredetails).
ItisrecommendedtousevaluewhentheonlyattributeontheannotationistheurlpatternandtousetheurlPatternsattributewhentheotherattributesarealsoused.
ItisillegaltohavebothvalueandurlPatternsattributeusedtogetheronthesameannotation.
ThedefaultnameoftheServletifnotspecifiedisthefullyqualifiedclassname.
TheannotatedservletMUSTspecifyatleastoneurlpatterntobedeployed.
Ifthesameservletclassisdeclaredinthedeploymentdescriptorunderadifferentname,anewinstanceoftheservletMUSTbeinstantiated.
IfthesameservletclassisaddedwithadifferentnametotheServletContextviatheprogrammaticAPIdefinedinSection4.
4.
1,"ProgrammaticallyaddingandconfiguringServlets"onpage4-35,theattributevaluesdeclaredviathe@WebServletannotationMUSTbeignoredandanewinstanceoftheservletwiththenamespecifiedMUSTbecreated.
Classesannotatedwith@WebServletclassMUSTextendthejavax.
servlet.
http.
HttpServletclass.
Followingisanexampleofhowthisannotationwouldbeused.
CODEEXAMPLE8-1@WebServletAnnotationExample@WebServlet("/foo")publicclassCalculatorServletextendsHttpServlet{//.
.
.
}Followingisanexampleofhowthisannotationwouldbeusedwithsomemoreoftheattributesspecified.
CODEEXAMPLE8-2@WebServletannotationexampleusingotherannotationattributesspecified@WebServlet(name="MyServlet",urlPatterns={"/foo","/bar"})publicclassSampleUsingAnnotationAttributesextendsHttpServlet{publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres){}}Chapter8Annotationsandpluggability698.
1.
2@WebFilterThisannotationisusedtodefineaFilterinawebapplication.
Thisannotationisspecifiedonaclassandcontainsmetadataaboutthefilterbeingdeclared.
ThedefaultnameoftheFilterifnotspecifiedisthefullyqualifiedclassname.
TheurlPatternsattribute,servletNamesattributeorthevalueattributeoftheannotationMUSTbespecified.
Allotherattributesareoptionalwithdefaultsettings(seejavadocsformoredetails).
ItisrecommendedtousevaluewhentheonlyattributeontheannotationistheurlpatternandtousetheurlPatternsattributewhentheotherattributesarealsoused.
ItisillegaltohavebothvalueandurlPatternsattributeusedtogetheronthesameannotation.
Classesannotatedwith@WebFilterMUSTimplementjavax.
servlet.
Filter.
Followingisanexampleofhowthisannotationwouldbeused.
CODEEXAMPLE8-3@WebFilterannotationexample@WebFilter("/foo")publicclassMyFilterimplementsFilter{publicvoiddoFilter(HttpServletRequestreq,HttpServletResponseres){.
.
.
}}8.
1.
3@WebInitParamThisannotationisusedtospecifyanyinitparametersthatmustbepassedtotheServletortheFilter.
ItisanattributeoftheWebServletandWebFilterannotation.
8.
1.
4@WebListenerTheWebListenerannotationisusedtoannotatealistenertogeteventsforvariousoperationsontheparticularwebapplicationcontext.
Classesannotatedwith@WebListenerMUSTimplementoneofthefollowinginterfaces:javax.
servlet.
ServletContextListenerjavax.
servlet.
ServletContextAttributeListenerjavax.
servlet.
ServletRequestListenerjavax.
servlet.
ServletRequestAttributeListener70JavaServletSpecificationjavax.
servlet.
http.
HttpSessionListenerjavax.
servlet.
http.
HttpSessionAttributeListenerjavax.
servlet.
http.
HttpSessionIdListenerAnexample:@WebListenerpublicclassMyListenerimplementsServletContextListener{publicvoidcontextInitialized(ServletContextEventsce){ServletContextsc=sce.
getServletContext();sc.
addServlet("myServlet","Sampleservlet","foo.
bar.
MyServlet",null,-1);sc.
addServletMapping("myServlet",newString[]{"/urlpattern/*"});}}8.
1.
5@MultipartConfigThisannotation,whenspecifiedonaServlet,indicatesthattherequestitexpectsisoftypemime/multipart.
TheHttpServletRequestobjectofthecorrespondingservletMUSTmakeavailablethemimeattachmentsviathegetPartsandgetPartmethodstoiterateoverthevariousmimeattachments.
Thelocationattributeofthejavax.
servlet.
annotation.
MultipartConfigandtheelementoftheisinterpretedasanabsolutepathanddefaultstothevalueofthejavax.
servlet.
context.
tempdir.
Ifarelativepathisspecified,itwillberelativetothetempdirlocation.
ThetestforabsolutepathvsrelativepathMUSTbedoneviajava.
io.
File.
isAbsolute.
8.
1.
6Otherannotations/conventionsInadditiontotheseannotationsalltheannotationsdefinedinSection15.
5,"AnnotationsandResourceInjection"onpage15-189willcontinuetoworkinthecontextofthesenewannotations.
Bydefaultallapplicationswillhaveindex.
htm(l)andindex.
jspinthelistofwelcome-file-list.
Thedescriptormaytobeusedtooverridethesedefaultsettings.
Chapter8Annotationsandpluggability71TheorderinwhichtheListeners,Servletsareloadedfromthevariousframeworkjars/classesintheWEB-INF/classesorWEB-INF/libisunspecifiedwhenusingannotations.
Iforderingisimportantthenlookatthesectionformodularityofweb.
xmlandorderingofweb.
xmlandweb-fragment.
xmlbelow.
Theordercanbespecifiedinthedeploymentdescriptoronly.
8.
2Pluggability8.
2.
1Modularityofweb.
xmlUsingtheannotationsdefinedabovemakestheuseofweb.
xmloptional.
Howeverforoverridingeitherthedefaultvaluesorthevaluessetviaannotations,thedeploymentdescriptorisused.
Asbefore,ifthemetadata-completeelementissettotrueintheweb.
xmldescriptor,annotationsthatspecifydeploymentinformationpresentintheclassfilesandweb-fragmentsbundledinjarswillnotbeprocessed.
Itimpliesthatallthemetadatafortheapplicationisspecifiedviatheweb.
xmldescriptor.
Forbetterpluggabilityandlessconfigurationfordevelopers,inthisversion(Servlet3.
0)ofthespecificationweareintroducingthenotionofwebmoduledeploymentdescriptorfragments(webfragment).
Awebfragmentisapartoralloftheweb.
xmlthatcanbespecifiedandincludedinalibraryorframeworkjar'sMETA-INFdirectory.
AplainoldjarfileintheWEB-INF/libdirectorywithnoweb-fragment.
xmlisalsoconsideredafragment.
Anyannotationsspecifiedinitwillbeprocessedaccordingtotherulesdefinedin8.
2.
3.
Thecontainerwillpickupandusetheconfigurationaspertherulesdefinedbelow.
Awebfragmentisalogicalpartitioningofthewebapplicationinsuchawaythattheframeworksbeingusedwithinthewebapplicationcandefinealltheartifactswithoutaskingdeveloperstoeditoraddinformationintheweb.
xml.
Itcanincludealmostallthesameelementsthattheweb.
xmldescriptoruses.
HoweverthetoplevelelementforthedescriptorMUSTbeweb-fragmentandthecorrespondingdescriptorfileMUSTbecalledweb-fragment.
xml.
Theorderingrelatedelementsalsodifferbetweentheweb-fragment.
xmlandweb.
xmlSeethecorrespondingschemaforweb-fragmentsinthedeploymentdescriptorsectioninChapter14.
Ifaframeworkispackagedasajarfileandhasmetadatainformationintheformofdeploymentdescriptorthentheweb-fragment.
xmldescriptormustbeintheMETA-INF/directoryofthejarfile.
72JavaServletSpecificationIfaframeworkwantsitsMETA-INF/web-fragment.
xmlhonoredinsuchawaythatitaugmentsawebapplication'sweb.
xml,theframeworkmustbebundledwithinthewebapplication'sWEB-INF/libdirectory.
Inorderforanyothertypesofresources(e.
g.
,classfiles)oftheframeworktobemadeavailabletoawebapplication,itissufficientfortheframeworktobepresentanywhereintheclassloaderdelegationchainofthewebapplication.
Inotherwords,onlyJARfilesbundledinawebapplication'sWEB-INF/libdirectory,butnotthosehigherupintheclassloadingdelegationchain,needtobescannedforweb-fragment.
xmlDuringdeploymentthecontainerisresponsibleforscanningthelocationspecifiedaboveanddiscoveringtheweb-fragment.
xmlandprocessingthem.
Therequirementsaboutnameuniquenessthatexistcurrentlyforasingleweb.
xmlalsoapplytotheunionofaweb.
xmlandallapplicableweb-fragment.
xmlfiles.
AnexampleofwhatalibraryorframeworkcanincludeisshownbelowwelcomeWelcomeServletRequestListenerTheaboveweb-fragment.
xmlwouldbeincludedintheMETA-INF/directoryoftheframework'sjarfile.
Theorderinwhichconfigurationfromweb-fragment.
xmlandannotationsshouldbeappliedisundefined.
Iforderingisanimportantaspectforaparticularapplicationpleaseseerulesdefinedbelowonhowtoachievetheorderdesired.
Chapter8Annotationsandpluggability738.
2.
2Orderingofweb.
xmlandweb-fragment.
xmlSincethespecificationallowstheapplicationconfigurationresourcestobecomposedofmultipleconfigurationfiles(web.
xmlandweb-fragment.
xml),discoveredandloadedfromseveraldifferentplacesintheapplication,thequestionoforderingmustbeaddressed.
Thissectionspecifieshowconfigurationresourceauthorsmaydeclaretheorderingrequirementsoftheirartifacts.
Aweb-fragment.
xmlmayhaveatoplevelelementoftypejavaee:java-identifierType.
Therecanonlybeoneelementinaweb-fragment.
xml.
Ifaelementispresent,itmustbeconsideredfortheorderingofartifacts(unlesstheduplicatenameexceptionapplies,asdescribedbelow).
Twocasesmustbeconsideredtoallowapplicationconfigurationresourcestoexpresstheirorderingpreferences.
1.
Absoluteordering:anelementintheweb.
xml.
Therecanonlybeoneelementinaweb.
xml.
a.
Inthiscase,orderingpreferencesthatwouldhavebeenhandledbycase2belowmustbeignored.
b.
Theweb.
xmlandWEB-INF/classesMUSTbeprocessedbeforeanyoftheweb-fragmentslistedintheabsolute-orderingelement.
c.
AnyelementdirectchildrenoftheMUSTbeinterpretedasindicatingtheabsoluteorderinginwhichthosenamedweb-fragments,whichmayormaynotbepresent,mustbeprocessed.
d.
Theelementmaycontainzerooroneelement.
Therequiredactionforthiselementisdescribedbelow.
Iftheelementdoesnotcontainanelement,anyweb-fragmentnotspecificallymentionedwithinelementsMUSTbeignored.
Excludedjarsarenotscannedforannotatedservlets,filtersorlisteners.
However,ifaservlet,filterorlistenerfromanexcludedjarislistedinweb.
xmloranon-excludedweb-fragment.
xml,thenit'sannotationswillapplyunlessotherwiseexcludedbymetadata-complete.
ServletContextListenersdiscoveredinTLDfilesofexcludedjarsarenotabletoconfigurefiltersandservletsusingtheprogrammaticAPIs.
AnyattempttodosowillresultinanIllegalStateException.
IfadiscoveredServletContainerInitializerisloadedfromanexcludedjar,itwillbeignored.
Irrespectiveofthesettingofmetadata-complete,jarsexcludedbyelementsarenotscannedforclassestobehandledbyanyServletContainerInitializer.
e.
Duplicatenameexception:if,whentraversingthechildrenof,multiplechildrenwiththesameelementareencountered,onlythefirstsuchoccurrencemustbeconsidered.
74JavaServletSpecification2.
Relativeordering:anelementwithintheweb-fragment.
xml.
Therecanonlybeoneelementinaweb-fragment.
xml.
a.
Aweb-fragment.
xmlmayhaveanelement.
Ifso,thiselementmustcontainzerooroneelementandzerooroneelement.
Themeaningoftheseelementsisexplainedbelow.
b.
Theweb.
xmlandWEB-INF/classesMUSTbeprocessedbeforeanyoftheweb-fragmentslistedintheorderingelement.
c.
Duplicatenameexception:if,whentraversingtheweb-fragments,multiplememberswiththesameelementareencountered,theapplicationmustloganinformativeerrormessageincludinginformationtohelpfixtheproblem,andmustfailtodeploy.
Forexample,onewaytofixthisproblemisfortheusertouseabsoluteordering,inwhichcaserelativeorderingisignored.
d.
Considerthisabbreviatedbutillustrativeexample.
3web-fragments-MyFragment1,MyFragment2andMyFragment3arepartoftheapplicationthatalsoincludesaweb.
xml.
web-fragment.
xmlMyFragment1MyFragment2.
.
.
web-fragment.
xmlMyFragment2.
.
web-fragment.
xmlMyFragment3.
.
web.
xmlChapter8Annotationsandpluggability75.
.
.
Inthisexampletheprocessingorderwillbeweb.
xmlMyFragment3MyFragment2MyFragment1Theprecedingexampleillustratessome,butnotall,ofthefollowingprinciples.
meansthedocumentmustbeorderedbeforethedocumentwiththenamematchingwhatisspecifiedwithinthenestedelement.
meansthedocumentmustbeorderedafterthedocumentwiththenamematchingwhatisspecifiedwithinthenestedelement.
Thereisaspecialelementwhichmaybeincludedzerooronetimewithintheorelement,orzerooronetimedirectlywithintheelement.
Theelementmustbehandledasfollows.
Iftheelementcontainsanested,thedocumentwillbemovedtothebeginningofthelistofsorteddocuments.
Iftherearemultipledocumentsstating,theywillallbeatthebeginningofthelistofsorteddocuments,buttheorderingwithinthegroupofsuchdocumentsisunspecified.
Iftheelementcontainsanested,thedocumentwillbemovedtotheendofthelistofsorteddocuments.
Iftherearemultipledocumentsrequiring,theywillallbeattheendofthelistofsorteddocuments,buttheorderingwithinthegroupofsuchdocumentsisunspecified.
Withinaorelement,ifanelementispresent,butisnottheonlyelementwithinitsparentelement,theotherelementswithinthatparentmustbeconsideredintheorderingprocess.
Iftheelementappearsdirectlywithintheelement,theruntimemustensurethatanyweb-fragmentsnotexplicitlynamedinthesectionareincludedatthatpointintheprocessingorder.
Ifaweb-fragment.
xmlfiledoesnothaveanortheweb.
xmldoesnothaveanelementtheartifactsareassumedtonothaveanyorderingdependency.
76JavaServletSpecificationIftheruntimediscoverscircularreferences,aninformativemessagemustbelogged,andtheapplicationmustfailtodeploy.
Again,onecourseofactiontheusermaytakeistouseabsoluteorderingintheweb.
xml.
Thepreviousexamplecanbeextendedtoillustratethecasewhentheweb.
xmlcontainsanorderingsection.
web.
xmlMyFragment3MyFragment2.
.
.
Inthisexample,theorderingforthevariouselementswillbeweb.
xmlMyFragment3MyFragment2Someadditionalexamplescenariosareincludedbelow.
AlloftheseapplytorelativeorderingandnotabsoluteorderingDocumentA:CDocumentBDocumentC:Chapter8Annotationsandpluggability77DocumentD:noorderingDocumentE:noorderingDocumentF:BResultingparseorder:web.
xml,F,B,D,E,C,A.
Document:CDocumentB:DocumentC:noorderingDocumentD:DocumentE:78JavaServletSpecificationDocumentF:noorderingResultingparseordercanbeoneofthefollowing:B,E,F,,C,DB,E,F,,D,CE,B,F,,C,DE,B,F,,D,CE,B,F,D,,CE,B,F,D,,DDocumentA:BDocumentB:noorderingDocumentC:DocumentD:noorderingResultingparseorder:C,B,D,A.
Theparseordercouldalsobe:C,D,B,AorC,B,A,D8.
2.
3Assemblingthedescriptorfromweb.
xml,web-fragment.
xmlandannotationsIftheorderinwhichthelisteners,servlets,filtersareinvokedisimportanttoanapplicationthenadeploymentdescriptormustbeused.
Also,ifnecessary,theorderingelementdefinedabovecanbeused.
Asdescribedabove,whenusingChapter8Annotationsandpluggability79annotationstodefinethelisteners,servletsandfilters,theorderinwhichtheyareinvokedisunspecified.
Belowareasetofrulesthatapplyforassemblingthefinaldeploymentdescriptorfortheapplication:1.
Theorderforlisteners,servlets,filtersifrelevantmustbespecifiedineithertheweb-fragment.
xmlortheweb.
xml.
2.
Theorderingwillbebasedontheorderinwhichtheyaredefinedinthedescriptorandontheabsolute-orderingelementintheweb.
xmloranorderingelementintheweb-fragment.
xml,ifpresent.
a.
Filtersthatmatcharequestarechainedintheorderinwhichtheyaredeclaredintheweb.
xml.
b.
Servletsareinitializedeitherlazilyatrequestprocessingtimeoreagerlyduringdeployment.
Inthelattercase,theyareinitializedintheorderindicatedbytheirload-on-startupelements.
c.
Thelistenersareinvokedintheorderinwhichtheyaredeclaredintheweb.
xmlasspecifiedbelow:i.
Implementationsofjavax.
servlet.
ServletContextListenerareinvokedattheircontextInitializedmethodintheorderinwhichtheyhavebeendeclared,andattheircontextDestroyedmethodinreverseorder.
ii.
Implementationsofjavax.
servlet.
ServletRequestListenerareinvokedattheirrequestInitializedmethodintheorderinwhichtheyhavebeendeclared,andattheirrequestDestroyedmethodinreverseorder.
iii.
Implementationsofjavax.
servlet.
http.
HttpSessionListenerareinvokedattheirsessionCreatedmethodintheorderinwhichtheyhavebeendeclared,andattheirsessionDestroyedmethodinreverseorder.
iv.
Themethodsofimplementationofjavax.
servlet.
ServletContextAttributeListener,javax.
servlet.
ServletRequestAttributeListenerandjavax.
servlet.
HttpSessionAttributeListenerareinvokedintheorderinwhichtheyaredeclaredwhencorrespondingeventsarefired.
3.
Ifaservletisdisabledusingtheenabledelementintroducedintheweb.
xmlthentheservletwillnotbeavailableattheurl-patternspecifiedfortheservlet.
4.
Theweb.
xmlofthewebapplicationhasthehighestprecedencewhenresolvingconflictsbetweentheweb.
xml,web-fragment.
xmlandannotations.
80JavaServletSpecification5.
Ifmetadata-completeisnotspecifiedinthedescriptors,orissettofalseinthedeploymentdescriptor,thentheeffectivemetadatafortheapplicationisderivedbycombiningthemetadatapresentintheannotationsandthedescriptors.
Therulesformergingarespecifiedbelow-a.
Configurationsettingsinwebfragmentsareusedtoaugmentthosespecifiedinthemainweb.
xmlinsuchawayasiftheyhadbeenspecifiedinthesameweb.
xml.
b.
Theorderinwhichconfigurationsettingsofwebfragmentsareaddedtothoseinthemainweb.
xmlisasspecifiedaboveinSection8.
2.
2,"Orderingofweb.
xmlandweb-fragment.
xml"onpage8-73c.
Themetadata-completeattributewhensettotrueinthemainweb.
xml,isconsideredcompleteandscanningofannotationsandfragmentswillnotoccuratdeploymenttime.
Theabsolute-orderingandorderingelementswillbeignoredifpresent.
Whensettotrueonafragment,themetadata-completeattributeappliesonlytoscanningofannotationsinthatparticularjar.
d.
Webfragmentsaremergedintothemainweb.
xmlunlessthemetadata-completeissettotrue.
Themergingtakesplaceafterannotationprocessingonthecorrespondingfragment.
e.
Thefollowingareconsideredconfigurationconflictswhenaugmentingaweb.
xmlwithwebfragments:i.
Multipleelementswiththesamebutdifferentii.
Multipleelementswiththesamebutdifferentf.
Theaboveconfigurationconflictsareresolvedasfollows:i.
Configurationconflictsbetweenthemainweb.
xmlandawebfragmentareresolvedsuchthattheconfigurationintheweb.
xmltakesprecedence.
ii.
Configurationconflictsbetweentwowebfragments,wheretheelementatthecenteroftheconflictisnotpresentinthemainweb.
xml,willresultinanerror.
Aninformativemessagemustbelogged,andtheapplicationmustfailtodeploy.
g.
Aftertheaboveconflictshavebeenresolved,theseadditionalrulesareappliedi.
Elementsthatmaybedeclaredanynumberoftimesareadditiveacrosstheweb-fragmentsintheresultingweb.
xml.
Forexample,elementswithdifferentareadditive.
Chapter8Annotationsandpluggability81ii.
Elementsthatmaybedeclaredanynumberoftimes,ifspecifiedintheweb.
xmloverridesthevaluesspecifiedintheweb-fragmentswiththesamename.
iii.
Ifanelementwithaminimumoccurrenceofzero,andamaximumoccurrenceofone,ispresentinawebfragment,andmissinginthemainweb.
xml,themainweb.
xmlinheritsthesettingfromthewebfragment.
Iftheelementispresentinboththemainweb.
xmlandthewebfragment,theconfigurationsettinginthemainweb.
xmltakesprecedence.
Forexample,ifboththemainweb.
xmlandawebfragmentdeclarethesameservlet,andtheservletdeclarationinthewebfragmentspecifiesaelement,whereastheoneinthemainweb.
xmldoesnot,thentheelementfromthewebfragmentwillbeusedinthemergedweb.
xml.
iv.
Itisconsideredanerrorifanelementwithaminimumoccurrenceofzero,andamaximumoccurrenceofone,isspecifieddifferentlyintwowebfragments,whileabsentfromthemainweb.
xml.
Forexample,iftwowebfragmentsdeclarethesameservlet,butwithdifferentelements,andthesameservletisalsodeclaredinthemainweb.
xml,butwithoutany,thenanerrormustbereported.
v.
declarationsareadditive.
vi.
elementswiththesameareadditiveacrossweb-fragments.
specifiedintheweb.
xmloverridesvaluesspecifiedintheweb-fragmentswiththesame.
vii.
elementswiththesameareadditiveacrossweb-fragments.
specifiedintheweb.
xmloverridesvaluesspecifiedintheweb-fragmentswiththesame.
viii.
Multipleelementswiththesamearetreatedasasingledeclarationix.
Theweb.
xmlresultingfromthemergeisconsideredonlyifallitswebfragmentsaremarkedasaswell.
x.
Thetop-levelandit'schildrenelements,,andelementsofawebfragmentareignored.
xi.
jsp-property-groupisadditive.
Itisrecommendedthatjsp-configelementusetheurl-patternasopposedtoextensionmappingswhenbundlingstaticresourcesintheMETA-INF/resourcesdirectoryofajarfile.
FurthermoreJSPresourcesforafragmentshouldbeinasub-directorysameasthefragmentname,ifthereexistsone.
Thishelpspreventaweb-82JavaServletSpecificationfragment'sjsp-property-groupfromaffectingtheJSPsinthemaindocrootoftheapplicationandthejsp-property-groupfromaffectingtheJSPsinafragment'sMETA-INF/resourcesdirectory.
h.
Foralltheresourcereferenceelements(env-entry,ejb-ref,ejb-local-ref,service-ref,resource-ref,resource-env-ref,message-destination-ref,persistence-context-refandpersistence-unit-ref)thefollowingrulesapply:i.
Ifanyresourcereferenceelementispresentinawebfragment,andismissinginthemainweb.
xml,themainweb.
xmlinheritsthevaluefromthewebfragment.
Iftheelementispresentinboththemainweb.
xmlandthewebfragment,withthesamename,theweb.
xmltakesprecedence.
Noneofthechildelementsfromthefragmentaremergedintothemainweb.
xmlexceptfortheinjection-targetasspecifiedbelow.
Forexample,ifboththemainweb.
xmlandawebfragmentdeclareawiththesame,thefromtheweb.
xmlwillbeusedwithoutanychildelementsbeingmergedfromthefragmentexceptasdescribedbelow.
ii.
Ifaresourcereferenceelementisspecifiedintwofragments,whileabsentfromthemainweb.
xml,andalltheattributesandchildelementsoftheresourcereferenceelementareidentical,theresourcereferencewillbemergedintothemainweb.
xml.
Itisconsideredanerrorifaresourcereferenceelementhasthesamenamespecifiedintwofragments,whileabsentfromthemainweb.
xmlandtheattributesandchildelementsarenotidenticalinthetwofragments.
AnerrormustbereportedandtheapplicationMUSTfailtodeploy.
Forexample,iftwowebfragmentsdeclareawiththesameelementbutthetypeinoneisspecifiedasjavax.
sql.
DataSourcewhilethetypeintheotheristhatofaJavaMailresource,itisanerrorandtheapplicationwillfailtodeployiii.
Forresourcereferenceelementwiththesamenameelementsfromthefragmentswillbemergedintothemainweb.
xml.
i.
Inadditiontothemergingrulesforweb-fragment.
xmldefinedabove,thefollowingrulesapplywhenusingtheresourcereferenceannotations(@Resource,@Resources,@EJB,@EJBs,@WebServiceRef,@WebServiceRefs,@PersistenceContext,@PersistenceContexts,@PersistenceUnit,and@PersistenceUnits)Ifaresourcereferenceannotationisappliedonaclass,itisequivalenttodefiningaresource,howeveritisnotequivalenttodefininganinjection-target.
Therulesaboveapplyforinjection-targetelementinthiscase.
Chapter8Annotationsandpluggability83Ifaresourcereferenceannotationisusedonafielditisequivalenttodefiningtheinjection-targetelementintheweb.
xml.
Howeverifthereisnoinjection-targetelementinthedescriptorthentheinjection-targetfromthefragmentswillstillbemergedintotheweb.
xmlasdefinedabove.
Ifontheotherhandthereisaninjection-targetinthemainweb.
xmlandthereisaresourcereferenceannotationwiththesameresourcename,thenitisconsideredanoverridefortheresourcereferenceannotation.
Inthiscasesincethereisaninjection-targetspecifiedinthedescriptor,therulesdefinedabovewouldapplyinadditiontooverridingthevaluefortheresourcereferenceannotation.
j.
Ifadata-sourceelementisspecifiedintwofragments,whileabsentfromthemainweb.
xml,andalltheattributesandchildelementsofthedata-sourceelementareidentical,thedata-sourcewillbemergedintothemainweb.
xml.
Itisconsideredanerrorifadata-sourceelementhasthesamenamespecifiedintwofragments,whileabsentfromthemainweb.
xmlandtheattributesandchildelementsarenotidenticalinthetwofragments.
InsuchacaseanerrormustbereportedandtheapplicationMUSTfailtodeploy.
Belowaresomeexamplesthatshowtheoutcomeinthedifferentcases.
CODEEXAMPLE8-4web.
xml-noresource-refdefinitionFragment1web-fragment.
xml.
.
.
com.
foo.
Bar.
classbazTheeffectivemetadatawouldbe84JavaServletSpecification.
.
.
.
com.
foo.
Bar.
classbazCODEEXAMPLE8-5web.
xml.
.
.
Fragment1web-fragment.
xml.
.
.
com.
foo.
Bar.
classbazFragment2web-fragment.
xmlChapter8Annotationsandpluggability85.
.
.
com.
foo.
Bar2.
classbaz2Theeffectivemetadatawouldbe.
.
.
.
com.
foo.
Bar.
classbazcom.
foo.
Bar2.
classbaz286JavaServletSpecificationCODEEXAMPLE8-6web.
xmlcom.
foo.
Bar3.
classbaz3.
.
.
Fragment1web-fragment.
xml.
.
.
com.
foo.
Bar.
classbazFragment2web-fragment.
xml.
.
.
Chapter8Annotationsandpluggability87com.
foo.
Bar2.
classbaz2Theeffectivemetadatawouldbecom.
foo.
Bar3.
classbaz3com.
foo.
Bar.
classbazcom.
foo.
Bar2.
classbaz2.
.
.
88JavaServletSpecificationThefromfragment1and2willbemergedintothemainweb.
xmlk.
Ifthemainweb.
xmldoesnothaveanyelementspecifiedandweb-fragmentshavespecifiedthentheelementsfromthefragmentswillbemergedintothemainweb.
xml.
Howeverifinthemainweb.
xmlatleastoneelementisspecifiedthentheelementsfromthefragmentwillnotbemerged.
Itistheresponsibilityoftheauthoroftheweb.
xmltomakesurethatthelistiscomplete.
l.
Ifthemainweb.
xmldoesnothaveanyelementspecifiedandweb-fragmentshavespecifiedthentheelementsfromthefragmentswillbemergedintothemainweb.
xml.
Howeverifinthemainweb.
xmlatleastoneelementisspecifiedthentheelementsfromthefragmentwillnotbemerged.
Itistheresponsibilityoftheauthoroftheweb.
xmltomakesurethatthelistiscomplete.
m.
Afterprocessingtheweb-fragment.
xml,annotationsfromthecorrespondingfragmentareprocessedtocompletetheeffectivemetadataforthefragmentbeforeprocessingthenextfragment.
Thefollowingrulesareusedforprocessingannotations:n.
Anymetadataspecifiedviaanannotationthatisn'talreadypresentinthedescriptorwillbeusedtoaugmenttheeffectivedescriptor.
i.
Configurationspecifiedinthemainweb.
xmlorawebfragmenttakesprecedenceovertheconfigurationspecifiedviaannotations.
ii.
Foraservletdefinedviathe@WebServletannotation,tooverridevaluesviathedescriptor,thenameoftheservletinthedescriptorMUSTmatchthenameoftheservletspecifiedviatheannotation(explicitlyspecifiedorthedefaultname,ifoneisnotspecifiedviatheannotation).
iii.
Initparamsforservletsandfiltersdefinedviaannotations,willbeoverriddeninthedescriptorifthenameoftheinitparamexactlymatchesthenamespecifiedviatheannotation.
Initparamsareadditivebetweentheannotationsanddescriptors.
iv.
url-patterns,whenspecifiedinadescriptorforagivenservletnameoverridestheurlpatternsspecifiedviatheannotation.
v.
Forafilterdefinedviathe@WebFilterannotation,tooverridevaluesviathedescriptor,thenameofthefilterinthedescriptorMUSTmatchthenameofthefilterspecifiedviatheannotation(explicitlyspecifiedorthedefaultname,ifoneisnotspecifiedviatheannotation).
Chapter8Annotationsandpluggability89vi.
url-patternstowhichafilterisapplied,whenspecifiedinadescriptorforagivenfilternameoverridestheurlpatternsspecifiedviatheannotation.
vii.
DispatcherTypestowhichafilterapplies,whenspecifiedinadescriptorforagivenfilternameoverridestheDispatcherTypesspecifiedviatheannotation.
viii.
Thefollowingexamplesdemonstratessomeoftheaboverules-AServletdeclaredviaanannotationandpackagedwiththecorrespondingweb.
xmlinthedescriptor@WebServlet(urlPatterns="/MyPattern",initParams={@WebInitParam(name="ccc",value="333")})publicclasscom.
acme.
FooextendsHttpServlet{.
.
.
}web.
xmlcom.
acme.
FooFooaaa111com.
acme.
FooFumbbb22290JavaServletSpecificationFoo/foo/*Fum/fum/*Sincethenameoftheservletdeclaredviatheannotationdoesnotmatchthenameoftheservletdeclaredintheweb.
xml,theannotationspecifiesanewservletdeclarationinadditiontotheotherdeclarationsinweb.
xmlandisequivalentto:com.
acme.
Foocom.
acme.
Fooccc333Iftheaboveweb.
xmlwerereplacedwiththefollowingcom.
acme.
Foocom.
acme.
Fooaaa111com.
acme.
Foo/foo/*Thentheeffectivedescriptorwouldbeequivalenttocom.
acme.
FooChapter8Annotationsandpluggability91com.
acme.
Fooaaa111ccc333com.
acme.
Foo/foo/*8.
2.
4Sharedlibraries/runtimespluggabilityInadditiontosupportingfragmentsanduseofannotationsoneoftherequirementsisthatnotonlywebeabletoplug-inthingsthatarebundledintheWEB-INF/libbutalsopluginsharedcopiesofframeworks-includingbeingabletoplug-intothewebcontainerthingslikeJAX-WS,JAX-RSandJSFthatbuildontopofthewebcontainer.
TheServletContainerInitializerallowshandlingsuchausecaseasdescribedbelow.
TheServletContainerInitializerclassislookedupviathejarservicesAPI.
Foreachapplication,aninstanceoftheServletContainerInitializeriscreatedbythecontaineratapplicationstartuptime.
TheframeworkprovidinganimplementationoftheServletContainerInitializerMUSTbundleintheMETA-INF/servicesdirectoryofthejarfileafilecalledjavax.
servlet.
ServletContainerInitializer,asperthejarservicesAPI,thatpointstotheimplementationclassoftheServletContainerInitializer.
InadditiontotheServletContainerInitializerwealsohaveanannotation-HandlesTypes.
TheHandlesTypesannotationontheimplementationoftheServletContainerInitializerisusedtoexpressinterestinclassesthatmayhaveannotations(type,methodorfieldlevelannotations)specifiedinthevalueoftheHandlesTypesorifitextends/implementsonethoseclassesanywhereintheclass'supertypes.
TheHandlesTypesannotationisappliedirrespectiveofthesettingofmetadata-complete.
92JavaServletSpecificationWhenexaminingtheclassesofanapplicationtoseeiftheymatchanyofthecriteriaspecifiedbytheHandlesTypesannotationofaServletContainerInitializer,thecontainermayrunintoclassloadingproblemsifoneormoreoftheapplication'soptionalJARfilesaremissing.
Sincethecontainerisnotinapositiontodecidewhetherthesetypesofclassloadingfailureswillpreventtheapplicationfromworkingcorrectly,itmustignorethem,whileatthesametimeprovidingaconfigurationoptionthatwouldlogthem.
IfanimplementationofServletContainerInitializerdoesnothavethe@HandlesTypesannotation,oriftherearenomatchestoanyoftheHandlesTypespecified,thenitwillgetinvokedonceforeveryapplicationwithnullasthevalueoftheSet.
Thiswillallowfortheinitializertodeterminebasedontheresourcesavailableintheapplicationwhetheritneedstoinitializeaservlet/filterornot.
TheonStartupmethodoftheServletContainerInitializerwillbeinvokedwhentheapplicationiscomingupbeforeanyofthelistener'seventsarefired.
TheonStartupmethodoftheServletContainerInitializeriscalledwithaSetofClassesthateitherextend/implementtheclassesthattheinitializerexpressedinterestinorifitisannotatedwithanyoftheclassesspecifiedviathe@HandlesTypesannotation.
Aconcreteexamplebelowshowcaseshowthiswouldwork.
Let'staketheJAX-WSwebservicesruntime.
TheimplementationofJAX-WSruntimeisn'ttypicallybundledineachandeverywarfile.
TheimplementationwouldbundleanimplementationoftheServletContainerInitializer(shownbelow)andthecontainerwouldlookthatupusingtheservicesAPI(thejarfilewillbundleinit'sMETA-INF/servicesdirectoryafilecalledjavax.
servlet.
ServletContainerInitializerthatwillpointtotheJAXWSServletContainerInitializershownbelow).
@HandlesTypes(WebService.
class)JAXWSServletContainerInitializerimplementsServletContainerInitializer{publicvoidonStartup(Set>c,ServletContextctx)throwsServletException{//JAX-WSspecificcodeheretoinitializetheruntime//andsetupthemappingetc.
ServletRegistrationreg=ctx.
addServlet("JAXWSServlet","com.
sun.
webservice.
JAXWSServlet");reg.
addServletMapping("/foo");}Chapter8Annotationsandpluggability93TheframeworkjarfilecanalsobebundledinWEB-INF/libdirectoryofthewarfile.
IftheServletContainerInitializerisbundledinaJARfileinsidetheWEB-INF/libdirectoryofanapplication,it'sonStartupmethodwillbeinvokedonlyonceduringthestartupofthebundlingapplication.
If,ontheotherhand,theServletContainerInitializerisbundledinaJARfileoutsideoftheWEB-INF/libdirectory,butstilldiscoverablebytheruntime'sserviceproviderlookupmechanism,it'sonStartupmethodwillbeinvokedeverytimeanapplicationisstarted.
ImplementationsoftheServletContainerInitializerinterfacewillbediscoveredbytheruntime'sservicelookupmechanismoracontainerspecificmechanismthatissemanticallyequivalenttoit.
Ineithercase,ServletContainerInitializerservicesfromwebfragmentJARfilesthatareexcludedfromanabsoluteorderingMUSTbeignored,andtheorderinwhichtheseservicesarediscoveredMUSTfollowtheapplication'sclassloadingdelegationmodel.
8.
3JSPcontainerpluggabilityTheServletContainerInitializerandprogrammaticregistrationfeaturesmakeitpossibletoprovideaclearseparationofresponsibilitiesbetweentheServletandJSPcontainers,bymakingtheServletcontainerresponsibleforparsingonlyweb.
xmlandweb-fragment.
xmlresources,anddelegatingtheparsingofTagLibraryDescriptor(TLD)resourcestotheJSPcontainer.
Previously,awebcontainerhadtoscanTLDresourcesforanylistenerdeclarations.
WithServlet3.
0,thisresponsibilitymaybedelegatedtotheJSPcontainer.
AJSPcontainerthatisembeddedinaServlet3.
0compliantServletcontainermayprovideitsownServletContainerInitializerimplementation,searchtheServletContextpassedtoitsonStartupmethodforanyTLDresources,scanthoseresourcesforlistenerdeclarations,andregisterthecorrespondinglistenerswiththeServletContext.
Inaddition,priortoServlet3.
0,aJSPcontainerusedtohavetoscananapplication'sdeploymentdescriptorforanyjsp-configrelatedconfiguration.
WithServlet3.
0,theServletcontainermustmakeavailable,viatheServletContext.
getJspConfigDescriptormethod,anyjsp-configrelatedconfigurationfromtheapplication'sweb.
xmlandweb-fragment.
xmldeploymentdescriptors.
AnyServletContextListenersthatwerediscoveredinaTLDandregisteredprogrammaticallyarelimitedinthefunctionalitytheyprovide.
AnyattempttocallaServletContextAPImethodonthemthatwasaddedinServlet3.
0willresultinanUnsupportedOperationException.
94JavaServletSpecificationInaddition,aServlet3.
0compliantServletcontainermustprovideaServletContextattributewithnamejavax.
servlet.
context.
orderedLibs,whosevalue(oftypejava.
util.
List)containsthelistofnamesofJARfilesintheWEB-INF/libdirectoryoftheapplicationrepresentedbytheServletContext,orderedbytheirwebfragmentnames(withpossibleexclusionsiffragmentJARfileshavebeenexcludedfromabsolute-ordering),ornulliftheapplicationdoesnotspecifyanyabsoluteorrelativeordering.
8.
4ProcessingannotationsandfragmentsWebapplicationscanincludebothannotationsandtheweb.
xml/web-fragment.
xmldeploymentdescriptors.
Ifthereisnodeploymentdescriptor,orthereisonebutdoesnothavethemetadata-completesettotrue,web.
xml,web-fragment.
xmlandannotationsifusedintheapplicationmustbeprocessed.
Thefollowingtabledescribeswhetherornottoprocessannotationsandweb.
xmlfragments.
TABLE8-1AnnotationsandwebfragmentprocessingrequirementsDeploymentdescriptormetadata-completeprocessannotationsandwebfragmentsweb.
xml2.
5YesNoweb.
xml2.
5noyesweb.
xml3.
0yesnoweb.
xml3.
0noyes95CHAPTER9DispatchingRequestsWhenbuildingaWebapplication,itisoftenusefultoforwardprocessingofarequesttoanotherservlet,ortoincludetheoutputofanotherservletintheresponse.
TheRequestDispatcherinterfaceprovidesamechanismtoaccomplishthis.
Whenasynchronousprocessingisenabledontherequest,theAsyncContextallowsausertodispatchtherequestbacktotheservletcontainer.
9.
1ObtainingaRequestDispatcherAnobjectimplementingtheRequestDispatcherinterfacemaybeobtainedfromtheServletContextviathefollowingmethods:getRequestDispatchergetNamedDispatcherThegetRequestDispatchermethodtakesaStringargumentdescribingapathwithinthescopeoftheServletContext.
ThispathmustberelativetotherootoftheServletContextandbeginwitha'/',orbeempty.
Themethodusesthepathtolookupaservlet,usingtheservletpathmatchingrulesinChapter12,"MappingRequeststoServlets",wrapsitwithaRequestDispatcherobject,andreturnstheresultingobject.
Ifnoservletcanberesolvedbasedonthegivenpath,aRequestDispatcherisprovidedthatreturnsthecontentforthatpath.
ThegetNamedDispatchermethodtakesaStringargumentindicatingthenameofaservletknowntotheServletContext.
Ifaservletisfound,itiswrappedwithaRequestDispatcherobjectandtheobjectisreturned.
Ifnoservletisassociatedwiththegivenname,themethodmustreturnnull.
96JavaServletSpecificationToallowRequestDispatcherobjectstobeobtainedusingrelativepathsthatarerelativetothepathofthecurrentrequest(notrelativetotherootoftheServletContext),thegetRequestDispatchermethodisprovidedintheServletRequestinterface.
ThebehaviorofthismethodissimilartothemethodofthesamenameintheServletContext.
Theservletcontainerusesinformationintherequestobjecttotransformthegivenrelativepathagainstthecurrentservlettoacompletepath.
Forexample,inacontextrootedat'/'andarequestto/garden/tools.
html,arequestdispatcherobtainedviaServletRequest.
getRequestDispatcher("header.
html")willbehaveexactlylikeacalltoServletContext.
getRequestDispatcher("/garden/header.
html").
9.
1.
1QueryStringsinRequestDispatcherPathsTheServletContextandServletRequestmethodsthatcreateRequestDispatcherobjectsusingpathinformationallowtheoptionalattachmentofquerystringinformationtothepath.
Forexample,aDevelopermayobtainaRequestDispatcherbyusingthefollowingcode:ParametersspecifiedinthequerystringusedtocreatetheRequestDispatchertakeprecedenceoverotherparametersofthesamenamepassedtotheincludedservlet.
TheparametersassociatedwithaRequestDispatcherarescopedtoapplyonlyforthedurationoftheincludeorforwardcall.
9.
2UsingaRequestDispatcherTousearequestdispatcher,aservletcallseithertheincludemethodorforwardmethodoftheRequestDispatcherinterface.
Theparameterstothesemethodscanbeeithertherequestandresponseargumentsthatwerepassedinviatheservicemethodofthejavax.
servlet.
Servletinterface,orinstancesofsubclassesoftherequestandresponsewrapperclassesthatwereintroducedforversion2.
3ofthespecification.
Inthelattercase,thewrapperinstancesmustwraptherequestorresponseobjectsthatthecontainerpassedintotheservicemethod.
TheContainerProvidershouldensurethatthedispatchoftherequesttoatargetservletoccursinthesamethreadofthesameJVMastheoriginalrequest.
Stringpath="/raisins.
jsporderno=5";RequestDispatcherrd=context.
getRequestDispatcher(path);rd.
include(request,response);Chapter9DispatchingRequests979.
3TheIncludeMethodTheincludemethodoftheRequestDispatcherinterfacemaybecalledatanytime.
Thetargetservletoftheincludemethodhasaccesstoallaspectsoftherequestobject,butitsuseoftheresponseobjectismorelimited.
ItcanonlywriteinformationtotheServletOutputStreamorWriteroftheresponseobjectandcommitaresponsebywritingcontentpasttheendoftheresponsebuffer,orbyexplicitlycallingtheflushBuffermethodoftheServletResponseinterface.
Itcannotsetheadersorcallanymethodthataffectstheheadersoftheresponse,withtheexceptionoftheHttpServletRequest.
getSession()andHttpServletRequest.
getSession(boolean)methods.
Anyattempttosettheheadersmustbeignored,andanycalltoHttpServletRequest.
getSession()orHttpServletRequest.
getSession(boolean)thatwouldrequireaddingaCookieresponseheadermustthrowanIllegalStateExceptioniftheresponsehasbeencommitted.
IfthedefaultservletisthetargetofaRequestDispatch.
include()andtherequestedresourcedoesnotexist,thenthedefaultservletMUSTthrowFileNotFoundException.
Iftheexceptionisn'tcaughtandhandled,andtheresponsehasn'tbeencommitted,thestatuscodeMUSTbesetto500.
9.
3.
1IncludedRequestParametersExceptforservletsobtainedbyusingthegetNamedDispatchermethod,aservletthathasbeeninvokedbyanotherservletusingtheincludemethodofRequestDispatcherhasaccesstothepathbywhichitwasinvoked.
Thefollowingrequestattributesmustbeset:TheseattributesareaccessiblefromtheincludedservletviathegetAttributemethodontherequestobjectandtheirvaluesmustbeequaltotherequestURI,contextpath,servletpath,pathinfo,andquerystringoftheincludedservlet,respectively.
Iftherequestissubsequentlyincluded,theseattributesarereplacedforthatinclude.
javax.
servlet.
include.
request_urijavax.
servlet.
include.
context_pathjavax.
servlet.
include.
servlet_pathjavax.
servlet.
include.
path_infojavax.
servlet.
include.
query_string98JavaServletSpecificationIftheincludedservletwasobtainedbyusingthegetNamedDispatchermethod,theseattributesmustnotbeset.
9.
4TheForwardMethodTheforwardmethodoftheRequestDispatcherinterfacemaybecalledbythecallingservletonlywhennooutputhasbeencommittedtotheclient.
Ifoutputdataexistsintheresponsebufferthathasnotbeencommitted,thecontentmustbeclearedbeforethetargetservlet'sservicemethodiscalled.
Iftheresponsehasbeencommitted,anIllegalStateExceptionmustbethrown.
ThepathelementsoftherequestobjectexposedtothetargetservletmustreflectthepathusedtoobtaintheRequestDispatcher.
TheonlyexceptiontothisisiftheRequestDispatcherwasobtainedviathegetNamedDispatchermethod.
Inthiscase,thepathelementsoftherequestobjectmustreflectthoseoftheoriginalrequest.
BeforetheforwardmethodoftheRequestDispatcherinterfacereturnswithoutexception,theresponsecontentmustbesentandcommitted,andclosedbytheservletcontainer,unlesstherequestwasputintotheasynchronousmode.
IfanerroroccursinthetargetoftheRequestDispatcher.
forward()theexceptionmaybepropagatedbackthroughallthecallingfiltersandservletsandeventuallybacktothecontainer9.
4.
1QueryStringTherequestdispatchingmechanismisresponsibleforaggregatingquerystringparameterswhenforwardingorincludingrequests.
9.
4.
2ForwardedRequestParametersExceptforservletsobtainedbyusingthegetNamedDispatchermethod,aservletthathasbeeninvokedbyanotherservletusingtheforwardmethodofRequestDispatcherhasaccesstothepathoftheoriginalrequest.
Chapter9DispatchingRequests99Thefollowingrequestattributesmustbeset:ThevaluesoftheseattributesmustbeequaltothereturnvaluesoftheHttpServletRequestmethodsgetRequestURI,getContextPath,getServletPath,getPathInfo,getQueryStringrespectively,invokedontherequestobjectpassedtothefirstservletobjectinthecallchainthatreceivedtherequestfromtheclient.
TheseattributesareaccessiblefromtheforwardedservletviathegetAttributemethodontherequestobject.
Notethattheseattributesmustalwaysreflecttheinformationintheoriginalrequestevenunderthesituationthatmultipleforwardsandsubsequentincludesarecalled.
IftheforwardedservletwasobtainedbyusingthegetNamedDispatchermethod,theseattributesmustnotbeset.
9.
5ErrorHandlingIftheservletthatisthetargetofarequestdispatcherthrowsaruntimeexceptionoracheckedexceptionoftypeServletExceptionorIOException,itshouldbepropagatedtothecallingservlet.
AllotherexceptionsshouldbewrappedasServletExceptionsandtherootcauseoftheexceptionsettotheoriginalexception,asitshouldnotbepropagated.
9.
6ObtaininganAsyncContextAnobjectimplementingtheAsyncContextinterfacemaybeobtainedfromtheServletRequestviaoneofstartAsyncmethods.
OnceyouhaveanAsyncContext,youcanuseittoeithercompletetheprocessingoftherequestviathecomplete()methodoruseoneofthedispatchmethodsdescribedbelow.
javax.
servlet.
forward.
request_urijavax.
servlet.
forward.
context_pathjavax.
servlet.
forward.
servlet_pathjavax.
servlet.
forward.
path_infojavax.
servlet.
forward.
query_string100JavaServletSpecification9.
7TheDispatchMethodThefollowingmethodscanbeusedtodispatchrequestsfromtheAsyncContext:dispatch(path)ThedispatchmethodtakesaStringargumentdescribingapathwithinthescopeoftheServletContext.
ThispathmustberelativetotherootoftheServletContextandbeginwitha'/'.
dispatch(servletContext,path)ThedispatchmethodtakesaStringargumentdescribingapathwithinthescopeoftheServletContextspecified.
ThispathmustberelativetotherootoftheServletContextspecifiedandbeginwitha'/'.
dispatch()Thedispatchmethodtakesnoargument.
ItusestheoriginalURIasthepath.
IftheAsyncContextwasinitializedviathestartAsync(ServletRequest,ServletResponse)andtherequestpassedisaninstanceofHttpServletRequest,thenthedispatchistotheURIreturnedbyHttpServletRequest.
getRequestURI().
OtherwisethedispatchistotheURIoftherequestwhenitwaslastdispatchedbythecontainerOneofthedispatchmethodsoftheAsyncContextinterfacemaybecalledbytheapplicationwaitingfortheasynchronouseventtohappen.
Ifcomplete()hasbeencalledontheAsyncContext,anIllegalStateExceptionmustbethrown.
Allthevariationsofthedispatchmethodsreturnsimmediatelyanddonotcommittheresponse.
ThepathelementsoftherequestobjectexposedtothetargetservletmustreflectthepathspecifiedintheAsyncContext.
dispatch.
9.
7.
1QueryStringTherequestdispatchingmechanismisresponsibleforaggregatingquerystringparameterswhendispatchingrequests.
9.
7.
2DispatchedRequestParametersAservletthathasbeeninvokedbyusingthedispatchmethodofAsyncContexthasaccesstothepathoftheoriginalrequest.
Chapter9DispatchingRequests101Thefollowingrequestattributesmustbeset:ThevaluesoftheseattributesmustbeequaltothereturnvaluesoftheHttpServletRequestmethodsgetRequestURI,getContextPath,getServletPath,getPathInfo,getQueryStringrespectively,invokedontherequestobjectpassedtothefirstservletobjectinthecallchainthatreceivedtherequestfromtheclient.
TheseattributesareaccessiblefromthedispatchedservletviathegetAttributemethodontherequestobject.
Notethattheseattributesmustalwaysreflecttheinformationintheoriginalrequestevenunderthesituationthatmultipledispatchesarecalled.
javax.
servlet.
async.
request_urijavax.
servlet.
async.
context_pathjavax.
servlet.
async.
servlet_pathjavax.
servlet.
async.
path_infojavax.
servlet.
async.
query_string102JavaServletSpecification103CHAPTER10WebApplicationsAWebapplicationisacollectionofservlets,HTMLpages,classes,andotherresourcesthatmakeupacompleteapplicationonaWebserver.
TheWebapplicationcanbebundledandrunonmultiplecontainersfrommultiplevendors.
10.
1WebApplicationsWithinWebServersAWebapplicationisrootedataspecificpathwithinaWebserver.
Forexample,acatalogapplicationcouldbelocatedathttp://www.
mycorp.
com/catalog.
AllrequeststhatstartwiththisprefixwillberoutedtotheServletContextwhichrepresentsthecatalogapplication.
AservletcontainercanestablishrulesforautomaticgenerationofWebapplications.
Forexamplea~user/mappingcouldbeusedtomaptoaWebapplicationbasedat/home/user/public_html/.
Bydefault,aninstanceofaWebapplicationmustrunononeVMatanyonetime.
Thisbehaviorcanbeoverriddeniftheapplicationismarkedas"distributable"viaitsdeploymentdescriptor.
AnapplicationmarkedasdistributablemustobeyamorerestrictivesetofrulesthanisrequiredofanormalWebapplication.
Theserulesaresetoutthroughoutthisspecification.
10.
2RelationshiptoServletContextTheservletcontainermustenforceaonetoonecorrespondencebetweenaWebapplicationandaServletContext.
AServletContextobjectprovidesaservletwithitsviewoftheapplication.
104JavaServletSpecification10.
3ElementsofaWebApplicationAWebapplicationmayconsistofthefollowingitems:ServletsJSPPages1UtilityClassesStaticdocuments(HTML,images,sounds,etc.
)ClientsideJavaapplets,beans,andclassesDescriptivemetainformationthattiesalloftheaboveelementstogether10.
4DeploymentHierarchiesThisspecificationdefinesahierarchicalstructureusedfordeploymentandpackagingpurposesthatcanexistinanopenfilesystem,inanarchivefile,orinsomeotherform.
Itisrecommended,butnotrequired,thatservletcontainerssupportthisstructureasaruntimerepresentation.
10.
5DirectoryStructureAWebapplicationexistsasastructuredhierarchyofdirectories.
Therootofthishierarchyservesasthedocumentrootforfilesthatarepartoftheapplication.
Forexample,foraWebapplicationwiththecontextpath/cataloginaWebcontainer,theindex.
htmlfileatthebaseoftheWebapplicationhierarchyorinaJARfileinsideWEB-INF/libthatincludestheindex.
htmlunderMETA-INF/resourcesdirectorycanbeservedtosatisfyarequestfrom/catalog/index.
html.
Ifanindex.
htmlispresentbothintherootcontextandintheMETA-INF/resourcesdirectoryofaJARfileintheWEB-INF/libdirectoryoftheapplication,thenthefilethatisavailableintherootcontextMUSTbeused.
TherulesformatchingURLstocontextpatharelaidoutinChapter12,"MappingRequeststoServlets".
SincethecontextpathofanapplicationdeterminestheURLnamespaceofthecontentsoftheWebapplication,WebcontainersmustrejectWebapplicationsdefiningacontextpaththatcouldcausepotentialconflictsinthisURLnamespace.
Thismayoccur,forexample,byattemptingtodeployasecondWebapplicationwiththesamecontext1.
SeetheJavaServerPagesspecificationavailablefromhttp://java.
sun.
com/products/jsp.
Chapter10WebApplications105path.
Sincerequestsarematchedtoresourcesinacase-sensitivemanner,thisdeterminationofpotentialconflictmustbeperformedinacase-sensitivemanneraswell.
Aspecialdirectoryexistswithintheapplicationhierarchynamed"WEB-INF".
Thisdirectorycontainsallthingsrelatedtotheapplicationthataren'tinthedocumentrootoftheapplication.
MostoftheWEB-INFnodeisnotpartofthepublicdocumenttreeoftheapplication.
ExceptforstaticresourcesandJSPspackagedintheMETA-INF/resourcesofaJARfilethatresidesintheWEB-INF/libdirectory,nootherfilescontainedintheWEB-INFdirectorymaybeserveddirectlytoaclientbythecontainer.
However,thecontentsoftheWEB-INFdirectoryarevisibletoservletcodeusingthegetResourceandgetResourceAsStreammethodcallsontheServletContext,andmaybeexposedusingtheRequestDispatchercalls.
Hence,iftheApplicationDeveloperneedsaccess,fromservletcode,toapplicationspecificconfigurationinformationthathedoesnotwishtobeexposeddirectlytotheWebclient,hemayplaceitunderthisdirectory.
Sincerequestsarematchedtoresourcemappingsinacase-sensitivemanner,clientrequestsfor'/WEB-INF/foo','/WEb-iNf/foo',forexample,shouldnotresultincontentsoftheWebapplicationlocatedunder/WEB-INFbeingreturned,noranyformofdirectorylistingthereof.
ThecontentsoftheWEB-INFdirectoryare:The/WEB-INF/web.
xmldeploymentdescriptor.
The/WEB-INF/classes/directoryforservletandutilityclasses.
Theclassesinthisdirectorymustbeavailabletotheapplicationclassloader.
The/WEB-INF/lib/*.
jarareaforJavaARchivefiles.
Thesefilescontainservlets,beans,staticresourcesandJSPspackagedinaJARfileandotherutilityclassesusefultotheWebapplication.
TheWebapplicationclassloadermustbeabletoloadclassesfromanyofthesearchivefiles.
TheWebapplicationclassloadermustloadclassesfromtheWEB-INF/classesdirectoryfirst,andthenfromlibraryJARsintheWEB-INF/libdirectory.
Also,exceptforthecasewherestaticresourcesarepackagedinJARfiles,anyrequestsfromtheclienttoaccesstheresourcesinWEB-INF/directorymustbereturnedwithaSC_NOT_FOUND(404)response.
106JavaServletSpecification10.
5.
1ExampleofApplicationDirectoryStructureThefollowingisalistingofallthefilesinasampleWebapplication:10.
6WebApplicationArchiveFileWebapplicationscanbepackagedandsignedintoaWebARchiveformat(WAR)fileusingthestandardJavaarchivetools.
Forexample,anapplicationforissuetrackingmightbedistributedinanarchivefilecalledissuetrack.
war.
Whenpackagedintosuchaform,aMETA-INFdirectorywillbepresentwhichcontainsinformationusefultoJavaarchivetools.
ThisdirectorymustnotbedirectlyservedascontentbythecontainerinresponsetoaWebclient'srequest,thoughitscontentsarevisibletoservletcodeviathegetResourceandgetResourceAsStreamcallsontheServletContext.
Also,anyrequeststoaccesstheresourcesinMETA-INFdirectorymustbereturnedwithaSC_NOT_FOUND(404)response.
10.
7WebApplicationDeploymentDescriptorTheWebapplicationdeploymentdescriptor(seeChapter14,"DeploymentDescriptor"")includesthefollowingtypesofconfigurationanddeploymentinformation:ServletContextInitParametersSessionConfigurationServlet/JSPDefinitionsServlet/JSPMappings/index.
html/howto.
jsp/feedback.
jsp/images/banner.
gif/images/jumping.
gif/WEB-INF/web.
xml/WEB-INF/lib/jspbean.
jar/WEB-INF/lib/catalog.
jar!
/META-INF/resources/catalog/moreOffers/books.
html/WEB-INF/classes/com/mycorp/servlets/MyServlet.
class/WEB-INF/classes/com/mycorp/util/MyUtils.
classChapter10WebApplications107MIMETypeMappingsWelcomeFilelistErrorPagesSecurity10.
7.
1DependenciesOnExtensionsWhenanumberofapplicationsmakeuseofthesamecodeorresources,theywilltypicallybeinstalledaslibraryfilesinthecontainer.
ThesefilesareoftencommonorstandardAPIsthatcanbeusedwithoutsacrificingportability.
FilesusedonlybyoneorafewapplicationswillbemadeavailableforaccessaspartoftheWebapplication.
Thecontainermustprovideadirectoryfortheselibraries.
ThefilesplacedwithinthisdirectorymustbeavailableacrossallWebapplications.
Thelocationofthisdirectoryiscontainer-specific.
TheclassloadertheservletcontainerusesforloadingtheselibraryfilesmustbethesameforallWebapplicationswithinthesameJVM.
ThisclassloaderinstancemustbesomewhereinthechainofparentclassloadersoftheWebapplicationclassloader.
ApplicationdevelopersneedtoknowwhatextensionsareinstalledonaWebcontainer,andcontainersneedtoknowwhatdependenciesservletsinaWARhaveonsuchlibrariesinordertopreserveportability.
TheapplicationdeveloperdependingonsuchanextensionorextensionsmustprovideaMETA-INF/MANIFEST.
MFentryintheWARfilelistingallextensionsneededbytheWAR.
TheformatofthemanifestentryshouldfollowstandardJARmanifestformat.
DuringdeploymentoftheWebapplication,theWebcontainermustmakethecorrectversionsoftheextensionsavailabletotheapplicationfollowingtherulesdefinedbytheOptionalPackageVersioningmechanism(http://java.
sun.
com/j2se/1.
4/docs/guide/extensions/).
WebcontainersmustalsobeabletorecognizedeclareddependenciesexpressedinthemanifestentryofanyofthelibraryJARsundertheWEB-INF/libentryinaWAR.
IfaWebcontainerisnotabletosatisfythedependenciesdeclaredinthismanner,itshouldrejecttheapplicationwithaninformativeerrormessage.
10.
7.
2WebApplicationClassLoaderTheclassloaderthatacontainerusestoloadaservletinaWARmustallowthedevelopertoloadanyresourcescontainedinlibraryJARswithintheWARfollowingnormalJavaSEsemanticsusinggetResource.
AsdescribedintheJavaEElicenseagreement,servletcontainersthatarenotpartofaJavaEEproductshouldnotallowtheapplicationtooverrideJavaSEplatformclasses,suchasthoseinthejava.
*andjavax.
*namespaces,thatJavaSEdoesnotallowtobemodified.
Thecontainer108JavaServletSpecificationshouldnotallowapplicationstooverrideoraccessthecontainer'simplementationclasses.
ItisrecommendedalsothattheapplicationclassloaderbeimplementedsothatclassesandresourcespackagedwithintheWARareloadedinpreferencetoclassesandresourcesresidingincontainer-widelibraryJARs.
AnimplementationMUSTalsoguaranteethatforeverywebapplicationdeployedinacontainer,acalltoThread.
currentThread.
getContextClassLoader()MUSTreturnaClassLoaderinstancethatimplementsthecontractspecifiedinthissection.
Furthermore,theClassLoaderinstanceMUSTbeaseparateinstanceforeachdeployedwebapplication.
ThecontainerisrequiredtosetthethreadcontextClassLoaderasdescribedabovebeforemakinganycallbacks(includinglistenercallbacks)intothewebapplication,andsetitbacktotheoriginalClassLoader,oncethecallbackreturns.
10.
8ReplacingaWebApplicationAservershouldbeabletoreplaceanapplicationwithanewversionwithoutrestartingthecontainer.
Whenanapplicationisreplaced,thecontainershouldprovidearobustmethodforpreservingsessiondatawithinthatapplication.
10.
9ErrorHandling10.
9.
1RequestAttributesAWebapplicationmustbeabletospecifythatwhenerrorsoccur,otherresourcesintheapplicationareusedtoprovidethecontentbodyoftheerrorresponse.
Thespecificationoftheseresourcesisdoneinthedeploymentdescriptor.
IfthelocationoftheerrorhandlerisaservletoraJSPpage:TheoriginalunwrappedrequestandresponseobjectscreatedbythecontainerarepassedtotheservletorJSPpage.
TherequestpathandattributesaresetasifaRequestDispatcher.
forwardtotheerrorresourcehadbeenperformed.
Chapter10WebApplications109TherequestattributesinTABLE10-1mustbeset.
Theseattributesallowtheservlettogeneratespecializedcontentdependingonthestatuscode,theexceptiontype,theerrormessage,theexceptionobjectpropagated,andtheURIoftherequestprocessedbytheservletinwhichtheerroroccurred(asdeterminedbythegetRequestURIcall),andthelogicalnameoftheservletinwhichtheerroroccurred.
Withtheintroductionoftheexceptionobjecttotheattributeslistforversion2.
3ofthisspecification,theexceptiontypeanderrormessageattributesareredundant.
TheyareretainedforbackwardscompatibilitywithearlierversionsoftheAPI.
10.
9.
2ErrorPagesToallowdeveloperstocustomizetheappearanceofcontentreturnedtoaWebclientwhenaservletgeneratesanerror,thedeploymentdescriptordefinesalistoferrorpagedescriptions.
ThesyntaxallowstheconfigurationofresourcestobereturnedbythecontainereitherwhenaservletorfiltercallssendErrorontheresponseforspecificstatuscodes,oriftheservletgeneratesanexceptionorerrorthatpropagatestothecontainer.
IfthesendErrormethodiscalledontheresponse,thecontainerconsultsthelistoferrorpagedeclarationsfortheWebapplicationthatusethestatus-codesyntaxandattemptsamatch.
Ifthereisamatch,thecontainerreturnstheresourceasindicatedbythelocationentry.
Aservletorfiltermaythrowthefollowingexceptionsduringprocessingofarequest:runtimeexceptionsorerrorsServletExceptionsorsubclassesthereofIOExceptionsorsubclassesthereofTABLE10-1RequestAttributesandtheirtypesRequestAttributesTypejavax.
servlet.
error.
status_codejava.
lang.
Integerjavax.
servlet.
error.
exception_typejava.
lang.
Classjavax.
servlet.
error.
messagejava.
lang.
Stringjavax.
servlet.
error.
exceptionjava.
lang.
Throwablejavax.
servlet.
error.
request_urijava.
lang.
Stringjavax.
servlet.
error.
servlet_namejava.
lang.
String110JavaServletSpecificationTheWebapplicationmayhavedeclarederrorpagesusingtheexception-typeelement.
Inthiscasethecontainermatchestheexceptiontypebycomparingtheexceptionthrownwiththelistoferror-pagedefinitionsthatusetheexception-typeelement.
Amatchresultsinthecontainerreturningtheresourceindicatedinthelocationentry.
Theclosestmatchintheclasshierarchywins.
Ifnoerror-pagedeclarationcontaininganexception-typefitsusingtheclass-hierarchymatch,andtheexceptionthrownisaServletExceptionorsubclassthereof,thecontainerextractsthewrappedexception,asdefinedbytheServletException.
getRootCausemethod.
Asecondpassismadeovertheerrorpagedeclarations,againattemptingthematchagainsttheerrorpagedeclarations,butusingthewrappedexceptioninstead.
Error-pagedeclarationsusingtheexception-typeelementinthedeploymentdescriptormustbeuniqueuptotheclassnameoftheexception-type.
Similarly,error-pagedeclarationsusingthestatus-codeelementmustbeuniqueinthedeploymentdescriptoruptothestatuscode.
Ifanerror-pageelementinthedeploymentdescriptordoesnotcontainanexception-typeoranerror-codeelement,theerrorpageisadefaulterrorpage.
TheerrorpagemechanismdescribeddoesnotintervenewhenerrorsoccurwheninvokedusingtheRequestDispatcherorfilter.
doFiltermethod.
Inthisway,afilterorservletusingtheRequestDispatcherhastheopportunitytohandleerrorsgenerated.
Ifaservletgeneratesanerrorthatisnothandledbytheerrorpagemechanismasdescribedabove,thecontainermustensuretosendaresponsewithstatus500.
ThedefaultservletandcontainerwillusethesendErrormethodtosend4xxand5xxstatusresponses,sothattheerrormechanismmaybeinvoked.
ThedefaultservletandcontainerwillusethesetStatusmethodfor2xxand3xxresponsesandwillnotinvoketheerrorpagemechanism.
IftheapplicationisusingasynchronousoperationsasdescribedinSection2.
3.
3.
3,"Asynchronousprocessing"onpage2-10,itistheapplication'sresponsibilitytohandleallerrorsinapplicationcreatedthreads.
ThecontainerMAYtakecareoftheerrorsfromthethreadissuedviaAsyncContext.
start.
ForhandlingerrorsthatoccurduringAsyncContext.
dispatchseeSectionn,"AnyerrorsorexceptionsthatmayoccurduringtheexecutionofthedispatchmethodsMUSTbecaughtandhandledbythecontainerasfollows:"onpage2-16Chapter10WebApplications11110.
9.
3ErrorFiltersTheerrorpagemechanismoperatesontheoriginalunwrapped/unfilteredrequestandresponseobjectscreatedbythecontainer.
ThemechanismdescribedinSection6.
2.
5,"FiltersandtheRequestDispatcher"maybeusedtospecifyfiltersthatareappliedbeforeanerrorresponseisgenerated.
10.
10WelcomeFilesWebApplicationdeveloperscandefineanorderedlistofpartialURIscalledwelcomefilesintheWebapplicationdeploymentdescriptor.
ThedeploymentdescriptorsyntaxforthelistisdescribedintheWebapplicationdeploymentdescriptorschema.
ThepurposeofthismechanismistoallowthedeployertospecifyanorderedlistofpartialURIsforthecontainertouseforappendingtoURIswhenthereisarequestforaURIthatcorrespondstoadirectoryentryintheWARnotmappedtoaWebcomponent.
Thiskindofrequestisknownasavalidpartialrequest.
Theuseforthisfacilityismadeclearbythefollowingcommonexample:Awelcomefileof'index.
html'canbedefinedsothatarequesttoaURLlikehost:port/webapp/directory/,where'directory'isanentryintheWARthatisnotmappedtoaservletorJSPpage,isreturnedtotheclientas'host:port/webapp/directory/index.
html'.
IfaWebcontainerreceivesavalidpartialrequest,theWebcontainermustexaminethewelcomefilelistdefinedinthedeploymentdescriptor.
ThewelcomefilelistisanorderedlistofpartialURLswithnotrailingorleading/.
TheWebservermustappendeachwelcomefileintheorderspecifiedinthedeploymentdescriptortothepartialrequestandcheckwhetherastaticresourceintheWARismappedtothatrequestURI.
Ifnomatchisfound,theWebserverMUSTagainappendeachwelcomefileintheorderspecifiedinthedeploymentdescriptortothepartialrequestandcheckifaservletismappedtothatrequestURI.
TheWebcontainermustsendtherequesttothefirstresourceintheWARthatmatches.
Thecontainermaysendtherequesttothewelcomeresourcewithaforward,aredirect,oracontainerspecificmechanismthatisindistinguishablefromadirectrequest.
Ifnomatchingwelcomefileisfoundinthemannerdescribed,thecontainermayhandletherequestinamanneritfindssuitable.
Forsomeconfigurationsthismaymeanreturningadirectorylistingorforothersreturninga404response.
ConsideraWebapplicationwhere:112JavaServletSpecificationThedeploymentdescriptorliststhefollowingwelcomefiles.
ThestaticcontentintheWARisasfollowsArequestURIof/foowillberedirectedtoaURIof/foo/.
ArequestURIof/foo/willbereturnedas/foo/index.
html.
ArequestURIof/catalogwillberedirectedtoaURIof/catalog/.
ArequestURIof/catalog/willbereturnedas/catalog/default.
jsp.
ArequestURIof/catalog/index.
htmlwillcausea404notfoundArequestURIof/catalog/productswillberedirectedtoaURIof/catalog/products/.
ArequestURIof/catalog/products/willbepassedtothe"default"servlet,ifany.
Ifno"default"servletismapped,therequestmaycausea404notfound,maycauseadirectorylistingincludingshop.
jspandregister.
jsp,ormaycauseotherbehaviordefinedbythecontainer.
SeeSection12.
2,"SpecificationofMappings"forthedefinitionof"default"servlet.
AlloftheabovestaticcontentcanalsobepackagedinaJARfilewiththecontentlistedabovepackagedintheMETA-INF/resourcesdirectoryofthejarfile.
TheJARfilecanthenbeincludedintheWEB-INF/libdirectoryofthewebapplication.
10.
11WebApplicationEnvironmentServletcontainersthatarenotpartofaJavaEEtechnology-compliantimplementationareencouraged,butnotrequired,toimplementtheapplicationenvironmentfunctionalitydescribedinSection15.
2.
2,"WebApplicationindex.
htmldefault.
jsp/foo/index.
html/foo/default.
jsp/foo/orderform.
html/foo/home.
gif/catalog/default.
jsp/catalog/products/shop.
jsp/catalog/products/register.
jspChapter10WebApplications113EnvironmentandtheJavaEEspecification.
Iftheydonotimplementthefacilitiesrequiredtosupportthisenvironment,upondeployinganapplicationthatreliesonthem,thecontainershouldprovideawarning.
10.
12WebApplicationDeploymentWhenawebapplicationisdeployedintoacontainer,thefollowingstepsmustbeperformed,inthisorder,beforethewebapplicationbeginsprocessingclientrequests.
Instantiateaninstanceofeacheventlisteneridentifiedbyaelementinthedeploymentdescriptor.
ForinstantiatedlistenerinstancesthatimplementServletContextListener,callthecontextInitialized()method.
Instantiateaninstanceofeachfilteridentifiedbyaelementinthedeploymentdescriptorandcalleachfilterinstance'sinit()method.
Instantiateaninstanceofeachservletidentifiedbyaelementthatincludesaelementintheorderdefinedbytheload-on-startupelementvalues,andcalleachservletinstance'sinit()method.
10.
13Inclusionofaweb.
xmlDeploymentDescriptorAwebapplicationisNOTrequiredtocontainaweb.
xmlifitdoesNOTcontainanyServlet,Filter,orListenercomponentsorisusingannotationstodeclarethesame.
InotherwordsanapplicationcontainingonlystaticfilesorJSPpagesdoesnotrequireaweb.
xmltobepresent.
114JavaServletSpecification115CHAPTER11ApplicationLifecycleEvents11.
1IntroductionTheapplicationeventsfacilitygivestheWebApplicationDevelopergreatercontroloverthelifecycleoftheServletContextandHttpSessionandServletRequest,allowsforbettercodefactorization,andincreasesefficiencyinmanagingtheresourcesthattheWebapplicationuses.
11.
2EventListenersApplicationeventlistenersareclassesthatimplementoneormoreoftheservleteventlistenerinterfaces.
TheyareinstantiatedandregisteredintheWebcontaineratthetimeofthedeploymentoftheWebapplication.
TheyareprovidedbytheDeveloperintheWAR.
ServleteventlistenerssupporteventnotificationsforstatechangesintheServletContext,HttpSessionandServletRequestobjects.
ServletcontextlistenersareusedtomanageresourcesorstateheldataJVMlevelfortheapplication.
HTTPsessionlistenersareusedtomanagestateorresourcesassociatedwithaseriesofrequestsmadeintoaWebapplicationfromthesameclientoruser.
Servletrequestlistenersareusedtomanagestateacrossthelifecycleofservletrequests.
Asynclistenersareusedtomanageasynceventssuchastimeoutsandcompletionofasyncprocessing.
Theremaybemultiplelistenerclasseslisteningtoeacheventtype,andtheDevelopermayspecifytheorderinwhichthecontainerinvokesthelistenerbeansforeacheventtype.
116JavaServletSpecification11.
2.
1EventTypesandListenerInterfacesEventstypesandthelistenerinterfacesusedtomonitorthemareshowninthefollowingtables:TABLE11-1ServletContextEventsEventTypeDescriptionListenerInterfaceLifecycleTheservletcontexthasjustbeencreatedandisavailabletoserviceitsfirstrequest,ortheservletcontextisabouttobeshutdown.
javax.
servlet.
ServletContextListenerChangestoattributesAttributesontheservletcontexthavebeenadded,removed,orreplaced.
javax.
servlet.
ServletContextAttributeListenerTABLE11-2HTTPSessionEventsEventTypeDescriptionListenerInterfaceLifecycleAnHttpSessionhasbeencreated,invalidated,ortimedout.
javax.
servlet.
http.
HttpSessionListenerChangestoattributesAttributeshavebeenadded,removed,orreplacedonanHttpSession.
javax.
servlet.
httpHttpSessionAttributeListenerChangestoidTheidofHttpSessionhasbeenchanged.
javax.
servlet.
httpHttpSessionIdListenerSessionmigrationHttpSessionhasbeenactivatedorpassivated.
javax.
servlet.
httpHttpSessionActivationListenerObjectbindingObjecthasbeenboundtoorunboundfromHttpSessionjavax.
servlet.
httpHttpSessionBindingListenerChapter11ApplicationLifecycleEvents117FordetailsoftheAPI,refertotheAPIreference.
11.
2.
2AnExampleofListenerUseToillustrateauseoftheeventscheme,considerasimpleWebapplicationcontaininganumberofservletsthatmakeuseofadatabase.
TheDeveloperhasprovidedaservletcontextlistenerclassformanagementofthedatabaseconnection.
1.
Whentheapplicationstartsup,thelistenerclassisnotified.
Theapplicationlogsontothedatabase,andstorestheconnectionintheservletcontext.
2.
ServletsintheapplicationaccesstheconnectionasneededduringactivityintheWebapplication.
3.
WhentheWebserverisshutdown,ortheapplicationisremovedfromtheWebserver,thelistenerclassisnotifiedandthedatabaseconnectionisclosed.
11.
3ListenerClassConfiguration11.
3.
1ProvisionofListenerClassesTheDeveloperoftheWebapplicationprovideslistenerclassesimplementingoneormoreofthelistenerinterfacesinthejavax.
servletAPI.
Eachlistenerclassmusthaveapublicconstructortakingnoarguments.
ThelistenerclassesarepackagedintotheWAR,eitherundertheWEB-INF/classesarchiveentry,orinsideaJARintheWEB-INF/libdirectory.
TABLE11-3ServletRequestEventsEventTypeDescriptionListenerInterfaceLifecycleAservletrequesthasstartedbeingprocessedbyWebcomponents.
javax.
servlet.
ServletRequestListenerChangestoattributesAttributeshavebeenadded,removed,orreplacedonaServletRequest.
javax.
servlet.
ServletRequestAttributeListenerAsynceventsAtimeout,connectionterminationorcompletionofasyncprocessingjavax.
servlet.
AsyncListener118JavaServletSpecification11.
3.
2DeploymentDeclarationsListenerclassesaredeclaredintheWebapplicationdeploymentdescriptorusingthelistenerelement.
Theyarelistedbyclassnameintheorderinwhichtheyaretobeinvoked.
Unlikeotherlisteners,listenersoftypeAsyncListenermayonlyberegistered(withaServletRequest)programmatically.
11.
3.
3ListenerRegistrationTheWebcontainercreatesaninstanceofeachlistenerclassandregistersitforeventnotificationspriortotheprocessingofthefirstrequestbytheapplication.
TheWebcontainerregistersthelistenerinstancesaccordingtotheinterfacestheyimplementandtheorderinwhichtheyappearinthedeploymentdescriptor.
Duringwebapplicationexecution,listenersforthegiveneventsaremostlyinvokedintheirregistrationorders,buttherearesomeexceptions.
Forinstance,HttpSessionListener.
destoryareinvokedinreverseorder.
SeeSection8.
2.
3,"Assemblingthedescriptorfromweb.
xml,web-fragment.
xmlandannotations"fordetails.
11.
3.
4NotificationsAtShutdownOnapplicationshutdown,listenersarenotifiedinreverseordertotheirdeclarationswithnotificationstosessionlistenersprecedingnotificationstocontextlisteners.
Sessionlistenersmustbenotifiedofsessioninvalidationspriortocontextlistenersbeingnotifiedofapplicationshutdown.
11.
4DeploymentDescriptorExampleThefollowingexampleisthedeploymentgrammarforregisteringtwoservletcontextlifecyclelistenersandanHttpSessionlistener.
Supposethatcom.
acme.
MyConnectionManagerandcom.
acme.
MyLoggingModulebothimplementjavax.
servlet.
ServletContextListener,andthatcom.
acme.
MyLoggingModuleadditionallyimplementsjavax.
servlet.
http.
HttpSessionListener.
Also,theDeveloperwantsChapter11ApplicationLifecycleEvents119com.
acme.
MyConnectionManagertobenotifiedofservletcontextlifecycleeventsbeforecom.
acme.
MyLoggingModule.
Hereisthedeploymentdescriptorforthisapplication:11.
5ListenerInstancesandThreadingThecontainerisrequiredtocompleteinstantiationofthelistenerclassesinaWebapplicationpriortothestartofexecutionofthefirstrequestintotheapplication.
ThecontainermustmaintainareferencetoeachlistenerinstanceuntilthelastrequestisservicedfortheWebapplication.
AttributechangestoServletContextandHttpSessionobjectsmayoccurconcurrently.
Thecontainerisnotrequiredtosynchronizetheresultingnotificationstoattributelistenerclasses.
Listenerclassesthatmaintainstateareresponsiblefortheintegrityofthedataandshouldhandlethiscaseexplicitly.
11.
6ListenerExceptionsApplicationcodeinsidealistenermaythrowanexceptionduringoperation.
Somelistenernotificationsoccurunderthecalltreeofanothercomponentintheapplication.
Anexampleofthisisaservletthatsetsasessionattribute,wherethesessionlistenerthrowsanunhandledexception.
ThecontainermustallowunhandledexceptionstobehandledbytheerrorpagemechanismdescribedinMyListeningApplicationcom.
acme.
MyConnectionManagercom.
acme.
MyLoggingModuleRegistrationServlet.
.
.
etc120JavaServletSpecificationSection10.
9,"ErrorHandling".
Ifthereisnoerrorpagespecifiedforthoseexceptions,thecontainermustensuretosendaresponsebackwithstatus500.
Inthiscasenomorelistenersunderthateventarecalled.
Someexceptionsdonotoccurunderthecallstackofanothercomponentintheapplication.
AnexampleofthisisaSessionListenerthatreceivesanotificationthatasessionhastimedoutandthrowsanunhandledexception,orofaServletContextListenerthatthrowsanunhandledexceptionduringanotificationofservletcontextinitialization,orofaServletRequestListenerthatthrowsanunhandledexceptionduringanotificationoftheinitializationorthedestructionoftherequestobject.
Inthiscase,theDeveloperhasnoopportunitytohandletheexception.
ThecontainermayrespondtoallsubsequentrequeststotheWebapplicationwithanHTTPstatuscode500toindicateanapplicationerror.
Developerswishingnormalprocessingtooccurafteralistenergeneratesanexceptionmusthandletheirownexceptionswithinthenotificationmethods.
11.
7DistributedContainersIndistributedWebcontainers,HttpSessioninstancesarescopedtotheparticularJVMservicingsessionrequests,andtheServletContextobjectisscopedtotheWebcontainer'sJVM.
DistributedcontainersarenotrequiredtopropagateeitherservletcontexteventsorHttpSessioneventstootherJVMs.
ListenerclassinstancesarescopedtooneperdeploymentdescriptordeclarationperJVM.
11.
8SessionEventsListenerclassesprovidetheDeveloperwithawayoftrackingsessionswithinaWebapplication.
Itisoftenusefulintrackingsessionstoknowwhetherasessionbecameinvalidbecausethecontainertimedoutthesession,orbecauseaWebcomponentwithintheapplicationcalledtheinvalidatemethod.
ThedistinctionmaybedeterminedindirectlyusinglistenersandtheHttpSessionAPImethods.
121CHAPTER12MappingRequeststoServletsThemappingtechniquesdescribedinthischapterarerequiredforWebcontainersmappingclientrequeststoservlets.
112.
1UseofURLPathsUponreceiptofaclientrequest,theWebcontainerdeterminestheWebapplicationtowhichtoforwardit.
TheWebapplicationselectedmusthavethelongestcontextpaththatmatchesthestartoftherequestURL.
ThematchedpartoftheURListhecontextpathwhenmappingtoservlets.
TheWebcontainernextmustlocatetheservlettoprocesstherequestusingthepathmappingproceduredescribedbelow.
ThepathusedformappingtoaservletistherequestURLfromtherequestobjectminusthecontextpathandthepathparameters.
TheURLpathmappingrulesbelowareusedinorder.
Thefirstsuccessfulmatchisusedwithnofurthermatchesattempted:1.
Thecontainerwilltrytofindanexactmatchofthepathoftherequesttothepathoftheservlet.
Asuccessfulmatchselectstheservlet.
2.
Thecontainerwillrecursivelytrytomatchthelongestpath-prefix.
Thisisdonebysteppingdownthepathtreeadirectoryatatime,usingthe'/'characterasapathseparator.
Thelongestmatchdeterminestheservletselected.
3.
IfthelastsegmentintheURLpathcontainsanextension(e.
g.
.
jsp),theservletcontainerwilltrytomatchaservletthathandlesrequestsfortheextension.
Anextensionisdefinedasthepartofthelastsegmentafterthelast'.
'character.
1.
Versionsofthisspecificationpriorto2.
5madeuseofthesemappingtechniquesasasuggestionratherthanarequirement,allowingservletcontainerstoeachhavetheirdifferentschemesformappingclientrequeststoservlets.
122JavaServletSpecification4.
Ifneitherofthepreviousthreerulesresultinaservletmatch,thecontainerwillattempttoservecontentappropriatefortheresourcerequested.
Ifa"default"servletisdefinedfortheapplication,itwillbeused.
Manycontainersprovideanimplicitdefaultservletforservingcontent.
Thecontainermustusecase-sensitivestringcomparisonsformatching.
12.
2SpecificationofMappingsIntheWebapplicationdeploymentdescriptor,thefollowingsyntaxisusedtodefinemappings:Astringbeginningwitha'/'characterandendingwitha'/*'suffixisusedforpathmapping.
Astringbeginningwitha'*.
'prefixisusedasanextensionmapping.
Theemptystring("")isaspecialURLpatternthatexactlymapstotheapplication'scontextroot,i.
e.
,requestsoftheformhttp://host:port//.
Inthiscasethepathinfois'/'andtheservletpathandcontextpathisemptystring("").
Astringcontainingonlythe'/'characterindicatesthe"default"servletoftheapplication.
InthiscasetheservletpathistherequestURIminusthecontextpathandthepathinfoisnull.
Allotherstringsareusedforexactmatchesonly.
Iftheeffectiveweb.
xml(aftermerginginformationfromfragmentsandannotations)containsanyurl-patternsthataremappedtomultipleservletsthenthedeploymentmustfail.
12.
2.
1ImplicitMappingsIfthecontainerhasaninternalJSPcontainer,the*.
jspextensionismappedtoit,allowingJSPpagestobeexecutedondemand.
Thismappingistermedanimplicitmapping.
Ifa*.
jspmappingisdefinedbytheWebapplication,itsmappingtakesprecedenceovertheimplicitmapping.
Aservletcontainerisallowedtomakeotherimplicitmappingsaslongasexplicitmappingstakeprecedence.
Forexample,animplicitmappingof*.
shtmlcouldbemappedtoincludefunctionalityontheserver.
Chapter12MappingRequeststoServlets12312.
2.
2ExampleMappingSetConsiderthefollowingsetofmappings:Thefollowingbehaviorwouldresult:Notethatinthecaseof/catalog/index.
htmland/catalog/racecar.
bop,theservletmappedto"/catalog"isnotusedbecausethematchisnotexact.
TABLE12-1ExampleSetofMapsPathPatternServlet/foo/bar/*servlet1/baz/*servlet2/catalogservlet3*.
bopservlet4TABLE12-2IncomingPathsAppliedtoExampleMapsIncomingPathServletHandlingRequest/foo/bar/index.
htmlservlet1/foo/bar/index.
bopservlet1/bazservlet2/baz/index.
htmlservlet2/catalogservlet3/catalog/index.
html"default"servlet/catalog/racecar.
bopservlet4/index.
bopservlet4124JavaServletSpecification125CHAPTER13SecurityWebapplicationsarecreatedbyApplicationDeveloperswhogive,sell,orotherwisetransfertheapplicationtoaDeployerforinstallationintoaruntimeenvironment.
ApplicationDeveloperscommunicatethesecurityrequirementstotheDeployersandthedeploymentsystem.
Thisinformationmaybeconveyeddeclarativelyviatheapplication'sdeploymentdescriptor,byusingannotationswithintheapplicationcode,orprogrammaticallyviathesetServletSecuritymethodoftheServletRegistrationinterface.
ThischapterdescribestheServletcontainersecuritymechanismsandinterfacesandthedeploymentdescriptor,annotation,andprogrammaticmechanismsforconveyingthesecurityrequirementsofapplications.
13.
1IntroductionAwebapplicationcontainsresourcesthatcanbeaccessedbymanyusers.
Theseresourcesoftentraverseunprotected,opennetworkssuchastheInternet.
Insuchanenvironment,asubstantialnumberofwebapplicationswillhavesecurityrequirements.
Althoughthequalityassurancesandimplementationdetailsmayvary,servletcontainershavemechanismsandinfrastructureformeetingtheserequirementsthatsharesomeofthefollowingcharacteristics:Authentication:Themeansbywhichcommunicatingentitiesprovetooneanotherthattheyareactingonbehalfofspecificidentitiesthatareauthorizedforaccess.
Accesscontrolforresources:Themeansbywhichinteractionswithresourcesarelimitedtocollectionsofusersorprogramsforthepurposeofenforcingintegrity,confidentiality,oravailabilityconstraints.
DataIntegrity:Themeansusedtoprovethatinformationhasnotbeenmodifiedbyathirdpartywhileintransit.
126JavaServletSpecificationConfidentialityorDataPrivacy:Themeansusedtoensurethatinformationismadeavailableonlytouserswhoareauthorizedtoaccessit.
13.
2DeclarativeSecurityDeclarativesecurityreferstothemeansofexpressinganapplication'ssecuritymodelorrequirements,includingroles,accesscontrol,andauthenticationrequirementsinaformexternaltotheapplication.
Thedeploymentdescriptoristheprimaryvehiclefordeclarativesecurityinwebapplications.
TheDeployermapstheapplication'slogicalsecurityrequirementstoarepresentationofthesecuritypolicythatisspecifictotheruntimeenvironment.
Atruntime,theservletcontainerusesthesecuritypolicyrepresentationtoenforceauthenticationandauthorization.
Thesecuritymodelappliestothestaticcontentpartofthewebapplicationandtoservletsandfilterswithintheapplicationthatarerequestedbytheclient.
ThesecuritymodeldoesnotapplywhenaservletusestheRequestDispatchertoinvokeastaticresourceorservletusingaforwardoraninclude.
13.
3ProgrammaticSecurityProgrammaticsecurityisusedbysecurityawareapplicationswhendeclarativesecurityaloneisnotsufficienttoexpressthesecuritymodeloftheapplication.
ProgrammaticsecurityconsistsofthefollowingmethodsoftheHttpServletRequestinterface:authenticateloginlogoutgetRemoteUserisUserInRolegetUserPrincipalTheloginmethodallowsanapplicationtoperformusernameandpasswordcollection(asanalternativetoForm-BasedLogin).
Theauthenticatemethodsallowanapplicationtoinstigateauthenticationoftherequestcallerbythecontainerfromwithinanunconstrainedrequestcontext.
Chapter13Security127Thelogoutmethodisprovidedtoallowanapplicationtoresetthecalleridentityofarequest.
ThegetRemoteUsermethodreturnsthenameoftheremoteuser(thatis,thecaller)associated,bythecontainer,withtherequest.
TheisUserInRolemethoddeterminesiftheremoteuser(thatis,thecaller)associatedwiththerequestisinaspecifiedsecurityrole.
ThegetUserPrincipalmethoddeterminestheprincipalnameoftheremoteuser(thatis,thecaller)andreturnsajava.
security.
Principalobjectcorrespondingtotheremoteuser.
CallingthegetNamemethodonthePrincipalreturnedbygetUserPrincipalreturnsthenameoftheremoteuser.
TheseAPIsallowservletstomakebusinesslogicdecisionsbasedontheinformationobtained.
Ifnouserhasbeenauthenticated,thegetRemoteUsermethodreturnsnull,theisUserInRolemethodalwaysreturnsfalse,andthegetUserPrincipalmethodreturnsnull.
TheisUserInRolemethodtakesaStringargumentthatreferencesanapplicationrole.
ForeachdistinctrolereferenceusedinacalltoisUserInRole,Asecurity-role-refelementwithrole-namecorrespondingtotherolereferenceshouldbedeclaredinthedeploymentdescriptor.
Eachsecurity-role-refshouldcontainarole-linksub-elementwhosevalueisthenameoftheapplicationsecurityroletowhichtheapplicationembeddedrolereferenceislinked.
Thecontainerusesthesecurity-role-refwithrole-nameequaltotherolereferencetodeterminewhichsecurity-roletotesttheuserformembershipin.
Forexample,tomapthesecurityrolereference"FOO"tothesecurityrolewithrole-name"manager"thesyntaxwouldbe:Inthiscase,ifaservletcalledbyauserbelongingtothe"manager"securityroleweretocallisUserInRole("FOO")theresultwouldbetrue.
Ifnomatchingsecurity-role-refexistsforarolereferenceusedinacalltoisUserInRole,thecontainermustdefaulttotestingtheuserformembershipinthesecurity-rolewithrole-nameequaltotherolereferenceusedinthecall.
Therolename"*"shouldneverbeusedasanargumentincallingisUserInRole.
AnycalltoisUserInRolewith"*"mustreturnfalse.
Iftherole-nameofthesecurity-roletobetestedis"**",andtheapplicationhasNOTdeclaredanapplicationsecurity-rolewithrole-name"**",isUserInRolemustonlyreturntrueFOOmanager128JavaServletSpecificationiftheuserhasbeenauthenticated;thatis,onlywhengetRemoteUserandgetUserPrincipalwouldbothreturnanon-nullvalue.
Otherwise,thecontainermustchecktheuserformembershipintheapplicationrole.
Thedeclarationofsecurity-role-refelementsinformsthedeployeroftherolereferencesusedbytheapplicationandforwhichmappingsmustbedefined.
13.
4ProgrammaticSecurityPolicyConfigurationThissectiondefinestheannotationsandapisprovidedtoconfigurethesecurityconstraintsenforcedbytheServletContainer.
13.
4.
1@ServletSecurityAnnotationThe@ServletSecurityannotationprovidesanalternativemechanismfordefiningaccesscontrolconstraintsequivalenttothosethatcouldotherwisehavebeenexpresseddeclarativelyviasecurity-constraintelementsintheportabledeploymentdescriptororprogrammaticallyviathesetServletSecuritymethodoftheServletRegistrationinterface.
ServletcontainersMUSTsupporttheuseofthe@ServletSecurityannotationonclasses(andsubclassesthereof)thatimplementthejavax.
servlet.
Servletinterface.
packagejavax.
servlet.
annotation;@Inherited@Documented@Target(value=TYPE)@Retention(value=RUNTIME)public@interfaceServletSecurity{HttpConstraintvalue();HttpMethodConstraint[]httpMethodConstraints();Chapter13Security129}@HttpConstraintThe@HttpConstraintannotationisusedwithinthe@ServletSecurityannotationtorepresentthesecurityconstrainttobeappliedtoallHTTPprotocolmethodsforwhichacorresponding@HttpMethodConstraintdoesNOToccurwithinthe@ServletSecurityannotation.
Forthespecialcasewherean@HttpConstraintthatreturnsalldefaultvalues1occursincombinationwithatleastone@HttpMethodConstraintthatreturnsotherthanalldefaultvalues,the@HttpConstraintrepresentsthatnosecurityconstraintistobeappliedtoanyoftheHTTPprotocolmethodstowhichasecurityconstraintwouldotherwiseapply.
Thisexceptionismadetoensurethatsuchpotentiallynon-specificusesof@HttpConstraintdonotyieldconstraintsthatwillexplicitlyestablishunprotectedaccessforsuchmethods;giventhattheywouldnototherwisebecoveredbyaconstraint.
packagejavax.
servlet.
annotation;@Documented@Retention(value=RUNTIME)public@interfaceHttpConstraint{ServletSecurity.
EmptyRoleSemanticvalue();java.
lang.
String[]rolesAllowed();ServletSecurity.
TransportGuaranteetransportGuarantee();TABLE13-1TheServletSecurityInterfaceElementDescriptionDefaultvaluetheHttpConstraintthatdefinestheprotectiontobeappliedtoallHTTPmethodsthatareNOTrepresentedinthearrayreturnedbyhttpMethodConstraints.
@HttpConstrainthttpMethodConstraintsthearrayofHTTPmethodspecificconstraints.
{}1.
Frommethodsvalue(),rolesAllowed(),andtransportGuarantee().
130JavaServletSpecification}@HttpMethodConstraintThe@HttpMethodConstraintannotationisusedwithinthe@ServletSecurityannotationtorepresentsecurityconstraintsonspecificHTTPprotocolmessages.
packagejavax.
servlet.
annotation;@Documented@Retention(value=RUNTIME)public@interfaceHttpMethodConstraint{ServletSecurity.
EmptyRoleSemanticvalue();java.
lang.
String[]rolesAllowed();ServletSecurity.
TransportGuaranteetransportGuarantee();}TABLE13-2TheHttpConstraintInterfaceElementDescriptionDefaultvalueThedefaultauthorizationsemanticthatapplies(only)whenrolesAllowedreturnsan-emptyarray.
PERMITrolesAllowedAnarraycontainingthenamesoftheauthorizedroles{}transportGuaranteeThedataprotectionrequirementsthatmustbesatisfiedbytheconnectionsonwhichrequestsarrive.
NONETABLE13-3TheHttpMethodConstraintInterfaceElementDescriptionDefaultvalueTheHTTPprotocolmethodnameemptyRoleSemanticThedefaultauthorizationsemanticthatapplies(only)whenrolesAllowedreturnsanemptyarray.
PERMITrolesAllowedAnarraycontainingthenamesoftheauthorizedroles{}transportGuaranteeThedataprotectionrequirementsthatmustbesatisfiedbytheconnectionsonwhichrequestsarrive.
NONEChapter13Security131The@ServletSecurityannotationmaybespecifiedon(thatis,targetedto)aServletimplementationclass,anditsvalueisinheritedbysubclassesaccordingtotherulesdefinedforthe@Inheritedmeta-annotation.
Atmostoneinstanceofthe@ServletSecurityannotationmayoccuronaServletimplementationclass,andthe@ServletSecurityannotationMUSTNOTbespecifiedon(thatis,targetedto)aJavamethod.
Whenoneormore@HttpMethodConstraintannotationsaredefinedwithina@ServletSecurityannotation,each@HttpMethodConstraintdefinesthesecurity-constraintthatappliestotheHTTPprotocolmethodidentifiedwithinthe@HttpMethodConstraint.
Exceptforthecasewhereits@HttpConstraintreturnsalldefaultvalues,andwhereitcontainsatleastone@HttpMethodConstraintthatreturnsotherthanalldefaultvalues,the@ServletSecurityannotationdefinesanothersecurity-constraintthatappliestoallHTTPprotocolmethodsforwhichacorresponding@HttpMethodConstrainthasnotbeendefined.
Thesecurity-constraintelementsdefinedintheportabledeploymentdescriptorsareauthoritativeforalltheurl-patternsoccurringwithintheconstraints.
Whenasecurity-constraintintheportabledeploymentdescriptorincludesaurl-patternthatisanexactmatchforapatternmappedtoaclassannotatedwith@ServletSecurity,theannotationmusthavenoeffectontheconstraintsenforcedbytheServletcontaineronthepattern.
Whenmetadata-complete=trueisdefinedforaportabledeploymentdescriptor,the@ServletSecurityannotationdoesnotapplytoanyoftheurl-patternsmappedto(anyservletmappedto)theannotatedclassinthedeploymentdescriptor.
The@ServletSecurityannotationisnotappliedtotheurl-patternsofaServletRegistrationcreatedusingtheaddServlet(String,Servlet)methodoftheServletContextinterface,unlesstheServletwasconstructedbythecreateServletmethodoftheServletContextinterface.
Withtheexceptionslistedabove,whenaServletclassisannotatedwith@ServletSecurity,theannotationdefinesthesecurityconstraintsthatapplytoalltheurl-patternsmappedtoalltheServletsmappedtotheclass.
Whenaclasshasnotbeenannotatedwiththe@ServletSecurityannotation,theaccesspolicythatisappliedtoaservletmappedfromthatclassisestablishedbytheapplicablesecurity-constraintelements,ifany,inthecorrespondingportabledeploymentdescriptor,orbarringanysuchelements,bytheconstraints,ifany,establishedprogrammaticallyforthetargetservletviathesetServletSecuritymethodoftheServletRegistrationinterface.
132JavaServletSpecification13.
4.
1.
1ExamplesThefollowingexamplesdemonstratetheuseoftheServletSecurityannotation.
CODEEXAMPLE13-1forallHTTPmethods,noconstraints@ServletSecuritypublicclassExample1extendsHttpServlet{}CODEEXAMPLE13-2forallHTTPmethods,noauth-constraint,confidentialtransportrequired@ServletSecurity(@HttpConstraint(transportGuarantee=TransportGuarantee.
CONFIDENTIAL))publicclassExample2extendsHttpServlet{}CODEEXAMPLE13-3forallHTTPmethods,allaccessdenied@ServletSecurity(@HttpConstraint(EmptyRoleSemantic.
DENY))publicclassExample3extendsHttpServlet{}CODEEXAMPLE13-4forallHTTPmethods,auth-constraintrequiringmembershipinRoleR1@ServletSecurity(@HttpConstraint(rolesAllowed="R1"))publicclassExample4extendsHttpServlet{}CODEEXAMPLE13-5forAllHTTPmethodsexceptGETandPOST,noconstraints;formethodsGETandPOST,auth-constraintrequiringmembershipinRoleR1;forPOST,confidentialtransportrequired@ServletSecurity((httpMethodConstraints={@HttpMethodConstraint(value="GET",rolesAllowed="R1"),@HttpMethodConstraint(value="POST",rolesAllowed="R1",transportGuarantee=TransportGuarantee.
CONFIDENTIAL)})publicclassExample5extendsHttpServlet{}CODEEXAMPLE13-6forallHTTPmethodsexceptGETauth-constraintrequiringmembershipinRoleR1;forGET,noconstraints@ServletSecurity(value=@HttpConstraint(rolesAllowed="R1"),httpMethodConstraints=@HttpMethodConstraint("GET"))publicclassExample6extendsHttpServlet{}Chapter13Security133CODEEXAMPLE13-7forallHTTPmethodsexceptTRACE,auth-constraintrequiringmembershipinRoleR1;forTRACE,allaccessdenied@ServletSecurity(value=@HttpConstraint(rolesAllowed="R1"),httpMethodConstraints=@HttpMethodConstraint(value="TRACE",emptyRoleSemantic=EmptyRoleSemantic.
DENY))publicclassExample7extendsHttpServlet{}13.
4.
1.
2Mapping@ServletSecuritytosecurity-constraintThissectiondescribesthemappingofthe@ServletSecurityannotationtoitsequivalentrepresentationassecurity-constraintelements.
Itisprovidedtofacilitateenforcementusingtheexistingsecurity-constraintenforcementmechanismofthecontainer.
TheenforcementbyServletcontainers,ofthe@ServletSecurityannotationmustbeequivalentineffecttoenforcement,bythecontainer,ofthesecurity-constraintelementsresultingfromthemappingdefinedinthissection.
The@ServletSecurityannotationisusedtodefineonemethod-independent@HttpConstraintfollowedbyalistofzeroormore@HttpMethodConstraintspecifications.
Themethod-independentconstraintisappliedtoallHTTPmethodsforwhichnoHTTPmethod-specificconstrainthasbeendefined.
Whenno@HttpMethodConstraintelementsareincluded,a@ServletSecurityannotationcorrespondstoasinglesecurity-constraintelementcontainingaweb-resource-collectionthatcontainsnohttp-methodelements,andthuspertainstoallHTTPmethods.
Thefollowingexampledepictstherepresentationofa@ServletSecurityannotationwithnocontained@HttpMethodConstraintannotationsasasinglesecurity-constraintelement.
Theurl-patternelementsdefinedbythecorrespondingservlet(registration)wouldbeincludedintheweb-resource-collection,andthepresenceandvalueofanycontainedauth-constraintanduser-data-constraintelementswouldbedeterminedbythemappingofthe@HttpConstraintvalueasdefinedinSection13.
4.
1.
3,"Mapping@HttpConstraintand@HttpMethodConstrainttoXML.
"onpage13-135CODEEXAMPLE13-8mapping@ServletSecuritywithnocontained@HttpMethodConstraint@ServletSecurity(@HttpConstraint(rolesAllowed="Role1")).
.
.
134JavaServletSpecificationRole1Whenoneormore@HttpMethodConstraintelementsarespecified,themethod-independentconstraintcorrespondstoasinglesecurity-constraintcontainingaweb-resource-collectionthatcontainsonhttp-method-omissionforeachoftheHTTPmethodsnamedinthe@HttpMethodConstraintelements.
Thesecurity-constraintcontaininghttp-method-omissionelementsmustNOTbecreatedifthemethod-independentconstraintreturnsalldefaultvaluesandatleastone@HttpMethodConstraintdoesnot.
Each@HttpMethodConstraintcorrespondstoanothersecurity-constraintcontainingaweb-resource-collectioncontaininganhttp-methodelementnamingthecorrespondingHTTPmethod.
Thefollowingexampledepictsthemappingofa@ServletSecurityannotationwithasinglecontained@HttpMethodConstrainttotwosecurity-constraintelements.
Theurl-patternelementsdefinedbythecorrespondingservlet(registration)wouldbeincludedintheweb-resource-collectionofbothconstraints,andthepresenceandvalueofanycontainedauth-constraintanduser-data-constraintelementswouldbedeterminedbythemappingoftheassociated@HttpConstraintand@HttpMethodConstraintvaluesasdefinedinSection13.
4.
1.
3,"Mapping@HttpConstraintand@HttpMethodConstrainttoXML.
"onpage13-135CODEEXAMPLE13-9mapping@ServletSecuritywithcontained@HttpMethodConstraint@ServletSecurity(value=@HttpConstraint(rolesAllowed="Role1"),httpMethodConstraints=@HttpMethodConstraint(value="TRACE",emptyRoleSemantic=EmptyRoleSemantic.
DENY)).
.
.
TRACERole1Chapter13Security135.
.
.
TRACE13.
4.
1.
3Mapping@HttpConstraintand@HttpMethodConstrainttoXML.
Thissectiondescribesthemappingofthe@HttpConstraintand@HttpMethodConstraintannotationvalues(definedforusewithin@ServletSecurity)totheircorrespondingauth-constraintanduser-data-constraintrepresentations,Theseannotationsshareacommonmodelforexpressingtheequivalentoftheauth-constraintanduser-data-constraintelementsusedwithintheportabledeploymentdescriptor.
Thatmodeliscomposedofthefollowing3elements:emptyRoleSemantictheauthorizationsemantic,eitherPERMITorDENY,thatapplieswhennorolesarenamedinrolesAllowed.
ThedefaultvalueforthiselementisPERMIT,andDENYisnotsupportedincombinationwithanon-emptyrolesAllowedlist.
rolesAllowedAlistcontainingthenamesoftheauthorizedroles.
Whenthislistisempty,itsmeaningdependsonthevalueoftheemptyRoleSemantic.
Therolename"*"hasnospecialmeaningwhenincludedinthelistofallowedroles.
Whenthespecialrolename"**"appearsinrolesAllowed,itindicatesthatuserauthentication,independentofrole,isrequiredandsufficient.
Thedefaultvalueforthiselementisanemptylist.
transportGuaranteeThedataprotectionrequirements,eitherNONEorCONFIDENTIAL,thatmustbesatisfiedbytheconnectionsonwhichrequestsarrive.
Thiselementisequivalentinmeaningtoauser-data-constraintcontainingatransport-guaranteewiththecorrespondingvalue.
ThedefaultvalueforthiselementisNONE.
Thefollowingexamplesdepictthecorrespondencebetweenthe@HttpConstraintmodeldescribedaboveandauth-constraintanduser-data-constraintelementsinweb.
xml.
CODEEXAMPLE13-10emptyRoleSemantic=PERMIT,rolesAllowed={},transportGuarantee=NONEnoconstraintsCODEEXAMPLE13-11emptyRoleSemantic=PERMIT,rolesAllowed={},transportGuarantee=CONFIDENTIAL136JavaServletSpecificationCONFIDENTIALCODEEXAMPLE13-12emptyRoleSemantic=PERMIT,rolesAllowed={Role1},transportGuarantee=NONERole1CODEEXAMPLE13-13emptyRoleSemantic=PERMIT,rolesAllowed={Role1},transportGuarantee=CONFIDENTIALRole1CONFIDENTIALCODEEXAMPLE13-14emptyRoleSemantic=DENY,rolesAllowed={},transportGuarantee=NONECODEEXAMPLE13-15emptyRoleSemantic=DENY,rolesAllowed={},transportGuarantee=CONFIDENTIALCONFIDENTIAL13.
4.
2setServletSecurityofServletRegistration.
DynamicThesetServletSecuritymethodmaybeusedwithinaServletContextListenertodefinethesecurityconstraintstobeappliedtothemappingsdefinedforaServletRegistration.
CollectionsetServletSecurity(ServletSecurityElementarg);Thejavax.
servlet.
ServletSecurityElementargumenttosetServletSecurityisanalogousinstructureandmodeltotheServletSecurityinterfaceofthe@ServletSecurityannotation.
Assuch,theChapter13Security137mappingsdefinedinSection13.
4.
1.
2,"Mapping@ServletSecuritytosecurity-constraint"onpage13-133,applyanalogouslytothemappingofaServletSecurityElementwithcontainedHttpConstraintElementandHttpMethodConstraintElementvalues,toitsequivalentsecurity-constraintrepresentation.
ThesetServletSecuritymethodreturnsthe(possiblyempty)SetofURLpatternsthatarealreadytheexacttargetofasecurity-constraintelementintheportabledeploymentdescriptor(andthuswereunaffectedbythecall).
ThismethodthrowsanIllegalStateExceptioniftheServletContextfromwhichtheServletRegistrationwasobtainedhasalreadybeeninitialized.
Whenasecurity-constraintintheportabledeploymentdescriptorincludesaurl-patternthatisanexactmatchforapatternmappedbyaServletRegistration,callstosetServletSecurityontheServletRegistrationmusthavenoeffectontheconstraintsenforcedbytheServletcontaineronthepattern.
WiththeexceptionslistedaboveandincludingwhentheServletclassisannotatedwith@ServletSecurity,whensetServletSecurityiscalledonaServletRegistrationitestablishesthesecurityconstraintsthatapplytotheurl-patternsoftheregistration.
13.
5RolesAsecurityroleisalogicalgroupingofusersdefinedbytheApplicationDeveloperorAssembler.
Whentheapplicationisdeployed,rolesaremappedbyaDeployertoprincipalsorgroupsintheruntimeenvironment.
Aservletcontainerenforcesdeclarativeorprogrammaticsecurityfortheprincipalassociatedwithanincomingrequestbasedonthesecurityattributesoftheprincipal.
Thismayhappenineitherofthefollowingways:1.
Adeployerhasmappedasecurityroletoausergroupintheoperationalenvironment.
Theusergroupstowhichthecallingprincipalbelongsareretrievedfromitssecurityattributes.
Theprincipalisinthesecurityroleonlyiftheprincipalbelongstotheusergrouptowhichthesecurityrolehasbeenmappedbythedeployer.
138JavaServletSpecification2.
Adeployerhasmappedasecurityroletoaprincipalnameinasecuritypolicydomain.
Inthiscase,theprincipalnameofthecallingprincipalisretrievedfromitssecurityattributes.
Theprincipalisinthesecurityroleonlyiftheprincipalnameisthesameasaprincipalnametowhichthesecurityrolewasmapped.
13.
6AuthenticationAwebclientcanauthenticateausertoawebserverusingoneofthefollowingmechanisms:HTTPBasicAuthenticationHTTPDigestAuthenticationHTTPSClientAuthenticationFormBasedAuthentication13.
6.
1HTTPBasicAuthenticationHTTPBasicAuthentication,whichisbasedonausernameandpassword,istheauthenticationmechanismdefinedintheHTTP/1.
0specification.
Awebserverrequestsawebclienttoauthenticatetheuser.
Aspartoftherequest,thewebserverpassestherealm(astring)inwhichtheuseristobeauthenticated.
Thewebclientobtainstheusernameandthepasswordfromtheuserandtransmitsthemtothewebserver.
Thewebserverthenauthenticatestheuserinthespecifiedrealm.
BasicAuthenticationisnotasecureauthenticationprotocol.
Userpasswordsaresentinsimplebase64encoding,andthetargetserverisnotauthenticated.
Additionalprotectioncanalleviatesomeoftheseconcerns:asecuretransportmechanism(HTTPS),orsecurityatthenetworklevel(suchastheIPSECprotocolorVPNstrategies)isappliedinsomedeploymentscenarios.
13.
6.
2HTTPDigestAuthenticationLikeHTTPBasicAuthentication,HTTPDigestAuthenticationauthenticatesauserbasedonausernameandapassword.
However,unlikeHTTPBasicAuthentication,HTTPDigestAuthenticationdoesnotsenduserpasswordsoverthenetwork.
InHTTPDigestauthenticationtheclientsendsaone-waycryptographichashofthepassword(andadditionaldata).
Althoughpasswordsarenotsentonthewire,HTTPDigestauthenticationrequiresthatcleartextpasswordequivalents2beavaialbleto2.
Thepasswordequivalentscanbesuchthattheycanonlybeusedtoauthenticateastheuserataspecificrealm.
Chapter13Security139theauthenticatingcontainersothatitcanvalidatereceivedauthenticatorsbycalculatingtheexpecteddigest.
ServletcontainersSHOULDsupportHTTP_DIGESTauthentication.
13.
6.
3FormBasedAuthenticationThelookandfeelofthe"loginscreen"cannotbevariedusingthewebbrowser'sbuilt-inauthenticationmechanisms.
ThisspecificationintroducesarequiredformbasedauthenticationmechanismwhichallowsaDevelopertocontrolthelookandfeeloftheloginscreens.
Thewebapplicationdeploymentdescriptorcontainsentriesforaloginformanderrorpage.
Theloginformmustcontainfieldsforenteringausernameandapassword.
Thesefieldsmustbenamedj_usernameandj_password,respectively.
Whenauserattemptstoaccessaprotectedwebresource,thecontainercheckstheuser'sauthentication.
Iftheuserisauthenticatedandpossessesauthoritytoaccesstheresource,therequestedwebresourceisactivatedandareferencetoitisreturned.
Iftheuserisnotauthenticated,allofthefollowingstepsoccur:1.
TheloginformassociatedwiththesecurityconstraintissenttotheclientandtheURLpathandHTTPprotocolmethodtriggeringtheauthenticationisstoredbythecontainer.
2.
Theuserisaskedtofillouttheform,includingtheusernameandpasswordfields.
3.
Theclientpoststheformbacktotheserver.
4.
Thecontainerattemptstoauthenticatetheuserusingtheinformationfromtheform.
5.
Ifauthenticationfails,theerrorpageisreturnedusingeitheraforwardoraredirect,andthestatuscodeoftheresponseissetto200.
Theerrorpagecontainsinformationaboutthefailure.
6.
Ifauthenticationsucceeds,theclientisredirectedtotheresourceusingthestoreURLpath.
7.
Whentheredirectedandauthenticatedrequestarrivesatthecontainer,thecontainerrestorestherequestandHTTPprotocolmethod,andtheauthenticateduser'sprincipalischeckedtoseeifitisinanauthorizedroleforaccessingtheresource.
8.
Iftheuserisauthorized,therequestisacceptedforprocessingbythecontainer.
140JavaServletSpecificationTheHTTPprotocolmethodoftheredirectedrequestthatarrivesinstep7,maydifferfromtheHTTPmethodoftherequestthattriggeredtheauthentication.
Assuch,followingtheredirectionofstep6,theformauthenticatormustprocesstheredirectedrequestevenifauthenticationisnotrequiredfortheHTTPmethodwithwhichtherequestarrives.
ToimprovethepredictabilityoftheHTTPmethodoftheredirectedrequest,containersshouldredirect(instep6)usingthe303(SC_SEE_OTHER)statuscode,exceptwhereinteroperabilitywithHTTP1.
0useragentsisrequired;inwhichcasesthe302statuscodeshouldbeused.
Whenconductedoveranunprotectedtransport,FormBasedAuthenticationissubjecttosomeofthesamevulnerabilitiesasBasicAuthentication.
Whentherequestthatistriggeringauthenticationarrivesoverasecuretransport,ortheloginpageissubjecttoauser-data-constraintofCONFIDENTIAL,theloginpagemustbereturnedtotheuser,andsubmittedtothecontaineroverasecuretransport.
Theloginpageshouldbesubjecttoauser-data-constraintofCONFIDENTIAL,andauser-data-constraintofCONFIDENTIALshouldbeincludedineverysecurity-constraintthatcontainsarequirementforauthentication.
TheloginmethodoftheHttpServletRequestinterfaceprovidesanalternativemeansforanapplicationtocontrolthelookandfeelofit'sloginscreens.
13.
6.
3.
1LoginFormNotesFormbasedloginandURLbasedsessiontrackingcanbeproblematictoimplement.
FormbasedloginshouldbeusedonlywhensessionsarebeingmaintainedbycookiesorbySSLsessioninformation.
Inorderfortheauthenticationtoproceedappropriately,theactionoftheloginformmustalwaysbej_security_check.
Thisrestrictionismadesothattheloginformwillworknomatterwhichresourceitisfor,andtoavoidrequiringtheservertospecifytheactionfieldoftheoutboundform.
Theloginformshouldspecifyautocomplete="off"onthepasswordformfield.
HereisanexampleshowinghowtheformshouldbecodedintotheHTMLpage:IftheformbasedloginisinvokedbecauseofanHTTPrequest,theoriginalrequestparametersmustbepreservedbythecontainerforuseif,onsuccessfulauthentication,itredirectsthecalltotherequestedresource.
Chapter13Security141IftheuserisauthenticatedusingformloginandhascreatedanHTTPsession,thetimeoutorinvalidationofthatsessionleadstotheuserbeingloggedoutinthesensethatsubsequentrequestsmustcausetheusertobere-authenticated.
Thescopeofthelogoutisthesameasthatoftheauthentication:forexample,ifthecontainersupportssinglesignon,suchasJavaEEtechnologycompliantwebcontainers,theuserwouldneedtoreauthenticatewithanyofthewebapplicationshostedonthewebcontainer.
13.
6.
4HTTPSClientAuthenticationEnduserauthenticationusingHTTPS(HTTPoverSSL)isastrongauthenticationmechanism.
ThismechanismrequirestheclienttopossessaPublicKeyCertificate(PKC).
Currently,PKCsareusefuline-commerceapplicationsandalsoforasingle-signonfromwithinthebrowser.
13.
6.
5AdditionalContainerAuthenticationMechanismsServletcontainersshouldprovidepublicinterfacesthatmaybeusedtointegrateandconfigureadditionalHTTPmessagelayerauthenticationmechanismsforusebythecontaineronbehalfofdeployedapplications.
Theseinterfacesshouldbeofferedforusebypartiesotherthanthecontainervendor(includingapplicationdevelopers,systemadministrators,andsystemintegrators).
Tofacilitateportableimplementationandintegrationofadditionalcontainerauthenticationmechanisms,itisrecommendedthatallServletcontainersimplementtheServletContainerProfileofTheJavatmAuthenticationSPIforContainers(i.
e.
,JSR196).
TheSPIisavailablefordownloadat:http://www.
jcp.
org/en/jsr/detailid=19613.
7ServerTrackingofAuthenticationInformationAstheunderlyingsecurityidentities(suchasusersandgroups)towhichrolesaremappedinaruntimeenvironmentareenvironmentspecificratherthanapplicationspecific,itisdesirableto:142JavaServletSpecification1.
Makeloginmechanismsandpoliciesapropertyoftheenvironmentthewebapplicationisdeployedin.
2.
Beabletousethesameauthenticationinformationtorepresentaprincipaltoallapplicationsdeployedinthesamecontainer,and3.
Requirere-authenticationofusersonlywhenasecuritypolicydomainboundaryhasbeencrossed.
Therefore,aservletcontainerisrequiredtotrackauthenticationinformationatthecontainerlevel(ratherthanatthewebapplicationlevel).
Thisallowsusersauthenticatedforonewebapplicationtoaccessotherresourcesmanagedbythecontainerpermittedtothesamesecurityidentity.
13.
8SpecifyingSecurityConstraintsSecurityconstraintsareadeclarativewayofdefiningtheprotectionofwebcontent.
AsecurityconstraintassociatesauthorizationandoruserdataconstraintswithHTTPoperationsonwebresources.
Asecurityconstraint,representedasasecurity-constraintinadeploymentdescriptor,consistsofthefollowingelements:webresourcecollection(web-resource-collectionindeploymentdescriptor)authorizationconstraint(auth-constraintindeploymentdescriptor)userdataconstraint(user-data-constraintindeploymentdescriptor)TheHTTPoperationsandwebresourcestowhichasecurityconstraintapplies(i.
e.
theconstrainedrequests)areidentifiedbyoneormorewebresourcecollections.
Awebresourcecollectionconsistsofthefollowingelements:URLpatterns(url-patternindeploymentdescriptor)HTTPmethods(http-methodorhttp-method-omissionelementsinthedeploymentdescriptor)Anauthorizationconstraintestablishesarequirementforauthenticationandnamestheauthorizationrolespermittedtoperformtheconstrainedrequests.
Ausermustbeamemberofatleastoneofthenamedrolestobepermittedtoperformtheconstrainedrequests.
Thespecialrolename"*"isashorthandforallrolenamesdefinedinthedeploymentdescriptor.
Thespecialrolename"**"isashorthandforanyauthenticateduserindependentofrole.
Whenthespecialrolename"**"appearsinanauthorizationconstraint,itindicatesthatanyauthenticateduser,independentofrole,isauthorizedtoperformtheconstrainedrequests.
Anauthorizationconstraintthatnamesnorolesindicatesthataccesstotheconstrainedrequestsmustnotbepermittedunderanycircumstances.
Anauthorizationconstraintconsistsofthefollowingelement:rolename(role-nameindeploymentdescriptor)Chapter13Security143Auserdataconstraintestablishesarequirementthattheconstrainedrequestsbereceivedoveraprotectedtransportlayerconnection.
Thestrengthoftherequiredprotectionisdefinedbythevalueofthetransportguarantee.
AtransportguaranteeofINTEGRALisusedtoestablisharequirementforcontentintegrityandatransportguaranteeofCONFIDENTIALisusedtoestablisharequirementforconfidentiality.
Thetransportguaranteeof"NONE"indicatesthatthecontainermustaccepttheconstrainedrequestswhenreceivedonanyconnectionincludinganunprotectedone.
ContainersmayimposeaconfidentialtransportguaranteeinresponsetotheINTEGRALvalue.
Auserdataconstraintconsistsofthefollowingelement:transportguarantee(transport-guaranteeindeploymentdescriptor)Ifnoauthorizationconstraintappliestoarequest,thecontainermustaccepttherequestwithoutrequiringuserauthentication.
Ifnouserdataconstraintappliestoarequest,thecontainermustaccepttherequestwhenreceivedoveranyconnectionincludinganunprotectedone.
13.
8.
1CombiningConstraintsForthepurposeofcombiningconstraints,anHTTPmethodissaidtooccurwithinaweb-resource-collectionwhennoHTTPmethodsarenamedinthecollection,orthecollectionspecificallynamestheHTTPmethodinacontainedhttp-methodelement,orthecollectioncontainsoneormorehttp-method-omissionelements,noneofwhichnamestheHTTPmethod.
Whenaurl-patternandHTTPmethodpairoccursincombination(i.
e,withinaweb-resource-collection)inmultiplesecurityconstraints,theconstraints(onthepatternandmethod)aredefinedbycombiningtheindividualconstraints.
Therulesforcombiningconstraintsinwhichthesamepatternandmethodoccurareasfollows:Thecombinationofauthorizationconstraintsthatnamerolesorthatimplyrolesviathename"*"shallyieldtheunionoftherolenamesintheindividualconstraintsaspermittedroles.
Anauthorizationconstraintthatnamestherole"**"shallcombinewithauthorizationconstraintsthatnameorimplyrolestopermitanyauthenticateduserindependentofrole.
Asecurityconstraintthatdoesnotcontainanauthorizationconstraintshallcombinewithauthorizationconstraintsthatnameorimplyrolestoallowunauthenticatedaccess.
Thespecialcaseofanauthorizationconstraintthatnamesnorolesshallcombinewithanyotherconstraintstooverridetheiraffectsandcauseaccesstobeprecluded.
Thecombinationofuser-data-constraintsthatapplytoacommonurl-patternandhttp-methodshallyieldtheunionofconnectiontypesacceptedbytheindividualconstraintsasacceptableconnectiontypes.
Asecurityconstraintthatdoesnotcontainauser-data-constraintshallcombinewithotheruser-data-constrainttocausetheunprotectedconnectiontypetobeanacceptedconnectiontype.
144JavaServletSpecification13.
8.
2ExampleThefollowingexampleillustratesthecombinationofconstraintsandtheirtranslationintoatableofapplicableconstraints.
Supposethatadeploymentdescriptorcontainedthefollowingsecurityconstraints.
precludedmethods/*/acme/wholesale/*/acme/retail/*GETPOSTwholesale/acme/wholesale/*GETPUTSALESCLERKChapter13Security145wholesale2/acme/wholesale/*GETPOSTCONTRACTORCONFIDENTIALretail/acme/retail/*GETPOSTCONTRACTORHOMEOWNER146JavaServletSpecificationThetranslationofthishypotheticaldeploymentdescriptorwouldyieldtheconstraintsdefinedinTABLE13-4.
13.
8.
3ProcessingRequestsWhenaServletcontainerreceivesarequest,itshallusethealgorithmdescribedin"UseofURLPaths"onpage121toselecttheconstraints(ifany)definedontheurl-patternthatisthebestmatchtotherequestURI.
Ifnoconstraintsareselected,thecontainershallaccepttherequest.
OtherwisethecontainershalldetermineiftheHTTPmethodoftherequestisconstrainedattheselectedpattern.
Ifitisnot,therequestshallbeaccepted.
Otherwise,therequestmustsatisfytheconstraintsthatapplytotheHTTPmethodattheurl-pattern.
Bothofthefollowingrulesmustbesatisfiedfortherequesttobeacceptedanddispatchedtotheassociatedservlet.
TABLE13-4SecurityConstraintTableurl-patternhttp-methodpermittedrolessupportedconnectiontypes/*allmethodsexceptGET,POSTaccessprecludednotconstrained/acme/wholesale/*allmethodsexceptGET,POSTaccessprecludednotconstrained/acme/wholesale/*GETCONTRACTORSALESCLERKnotconstrained/acme/wholesale/*POSTCONTRACTORCONFIDENTIAL/acme/retail/*allmethodsexceptGET,POSTaccessprecludednotconstrained/acme/retail/*GETCONTRACTORHOMEOWNERnotconstrained/acme/retail/*POSTCONTRACTORHOMEOWNERnotconstrainedChapter13Security1471.
Thecharacteristicsoftheconnectiononwhichtherequestwasreceivedmustsatisfyatleastoneofthesupportedconnectiontypesdefinedbytheconstraints.
Ifthisruleisnotsatisfied,thecontainershallrejecttherequestandredirectittotheHTTPSport.
32.
Theauthenticationcharacteristicsoftherequestmustsatisfyanyauthenticationandrolerequirementsdefinedbytheconstraints.
Ifthisruleisnotsatisfiedbecauseaccesshasbeenprecluded(byanauthorizationconstraintnamingnoroles),therequestshallberejectedasforbiddenanda403(SC_FORBIDDEN)statuscodeshallbereturnedtotheuser.
Ifaccessisrestrictedtopermittedrolesandtherequesthasnotbeenauthenticated,therequestshallberejectedasunauthorizedanda401(SC_UNAUTHORIZED)statuscodeshallbereturnedtocauseauthentication.
Ifaccessisrestrictedtopermittedrolesandtheauthenticationidentityoftherequestisnotamemberofanyoftheseroles,therequestshallberejectedasforbiddenanda403(SC_FORBIDDEN)statuscodeshallbereturnedtotheuser.
13.
8.
4UncoveredHTTPProtocolMethodsThesecurity-constraintschemaprovidestheabilitytoenumerate(includingbyomission)theHTTPprotocolmethodstowhichtheprotectionrequirementsdefinedinasecurity-constraintapply.
WhenHTTPmethodsareenumeratedwithinasecurity-constraint,theprotectionsdefinedbytheconstraintapplyonlytothemethodsestablishedbytheenumeration.
WerefertotheHTTPmethodsthatarenotestablishedbytheenumerationas"uncovered"HTTPmethods.
UncoveredHTTPmethodsareNOTprotectedatallrequestURLsforwhichaurl-patternofthesecurity-constraintisabestmatch.
WhenHTTPmethodsarenotenumeratedwithinasecurity-constraint,theprotectionsdefinedbytheconstraintapplytothecompletesetofHTTP(extension)methods.
Inthatcase,therearenouncoveredHTTPmethodsatallrequestURLsforwhichaurl-patternofthesecurity-constraintisabestmatch.
TheexamplesthatfollowdepictthethreewaysinwhichHTTPprotocolmethodsmaybeleftuncovered.
Thedeterminationofwhethermethodsareuncoveredismadeafteralltheconstraintsthatapplytoaurl-patternhavebeencombinedasdescribedinSection13.
8.
1,"CombiningConstraints"onpage13-143.
3.
Asanoptimization,acontainershouldrejecttherequestasforbiddenandreturna403(SC_FORBIDDEN)statuscodeifitknowsthataccesswillultimatelybeprecluded(byanauthorizationconstraintnamingnoroles).
148JavaServletSpecification1.
Asecurity-constraintnamesoneormoreHTTPmethodsinhttp-methodelements.
AllHTTPmethodsotherthanthosenamedintheconstraintareuncovered.
AllHTTPMethodsexceptGETareuncovered.
2.
Asecurity-constraintnamesoneormoreHTTPmethodsinhttp-method-omissionelements.
AllHTTPmethodsnamedintheconstraintareuncovered.
GETisuncovered.
Allothermethodsarecoveredbytheexcludingauth-contraint.
3.
A@ServletSecurityannotationincludesan@HttpConstraintthatreturnsalldefaultvaluesanditalsoincludesatleastone@HttpMethodConstraintthatreturnsotherthanalldefaultvalues.
AllHTTPmethodsotherthanthosenamedinan@HTTPMethodConstraintareuncoveredbytheannotation.
Thiscaseiswholesale/acme/wholesale/*GETSALESCLERKwholesale/acme/wholesale/*GETChapter13Security149analogoustocase1,andequivalentuseofthesetServletSecuritymethodoftheServletRegistrationinterfacewillalsoproduceananalogousresult.
AllHTTPMethodsexceptGETandPOSTareuncovered.
13.
8.
4.
1RulesforSecurityConstraintConfigurationObjective:MakesureallHTTPmethodsatallconstrainedURLpatternshavetheintendedsecurityprotections(thatis,arecovered).
1.
DonotnameHTTPmethodsinconstraints;inwhichcase,thesecurityprotectionsdefinedfortheURLpatternswillapplytoallHTTPmethods.
2.
Ifyoucan'tfollowrule#1,addtheanddeclare(usingtheelement,orequivalentannotation)alltheHTTPmethods(withsecurityprotections)thataretobeallowedattheconstrainedURLpatterns.
3.
Ifyoucan'tfollowrule#2,declareconstraintstocoverallHTTPmethodsateachconstrainedURLpattern.
UsetheelementortheHttpMethodConstraintannotationtorepresentthesetofallHTTPmethodsotherthanthosenamedbyorHttpMethodConstraint.
Whenusingannotations,usetheHttpConstraintannotationtodefinethesecuritysemantictobeappliedtoallotherHTTPmethodsandconfigureEmptyRoleSemantic=DENYtocauseallotherHTTPmethodstobedenied.
13.
8.
4.
2HandlingUncoveredHTTPMethodsDuringapplicationdeployment,thecontainermustinformthedeployerofanyuncoveredHTTPmethodspresentintheapplicationsecurityconstraintconfigurationresultingfromthecombinationoftheconstraintsdefinedfortheapplication.
TheprovidedinformationmustidentifytheuncoveredHTTPprotocolmethods,andthecorrespondingURLpatternsatwhichtheHTTPmethodsareuncovered.
Therequirementtonotifythedeployermaybesatisfiedbyloggingtherequiredinformation.
@ServletSecurity((httpMethodConstraints={@HttpMethodConstraint(value="GET",rolesAllowed="R1"),@HttpMethodConstraint(value="POST",rolesAllowed="R1",transportGuarantee=TransportGuarantee.
CONFIDENTIAL)})publicclassExample5extendsHttpServlet{}150JavaServletSpecificationWhenthedeny-uncovered-http-methodsflagissetintheweb.
xmlofanapplication,thecontainermustdenyanyHTTPprotocolmethodwhenitisusedwitharequestURLforwhichtheHTTPmethodisuncoveredatthecombinedsecurityconstraintthatappliestotheurl-patternthatisthebestmatchfortherequestURL.
Thedeniedrequestshallberejectedasforbiddenanda403(SC_FORBIDDEN)statuscodeshallbereturned.
TocauseuncoveredHTTPmethodstobedenied,thedeploymentsystemshouldestablishadditionalexcludingauth-constraints,tocovertheseHTTPmethodsattheconstrainedurl-patternsatwhichtheHTTPmethodsareuncovered.
Whenanapplication'ssecurityconfigurationcontainsnouncoveredmethods,thedeny-uncovered-http-methodsflagmusthavenoeffectontheeffectivesecurityconfigurationoftheapplication.
Applyingthedeny-uncovered-http-methodsflagtoanapplicationwhosesecurityconfigurationcontainsuncoveredmethods,may,insomecases,denyaccesstoresourcesthatmustbeaccessibleinorderfortheapplicationtofunction.
Insuchcases,thesecurityconfigurationoftheapplicationshouldbecompletedsuchthatalluncoveredmethodsarecoveredbyanappropriateconstraintconfiguration.
ApplicationDevelopersshoulddefinesecurityconstraintconfigurationsthatleavenoHTTPmethodsuncovered,andtheyshouldsetthedeny-uncovered-http-methodsflagtoensurethattheirapplicationsdonotbecomedependentonbeingaccessibleviauncoveredmethods.
AServletcontainermayprovideaconfigurableoptiontoselectwhetherthedefaultbehaviorforuncoveredmethodsisALLOWorDENY.
Thisoptionmaybeconfiguredonaper-applicationgranularityorlarger.
NotethatsettingthisdefaulttoDENYmaycausesomeapplicationstofail.
13.
9DefaultPoliciesBydefault,authenticationisnotneededtoaccessresources.
Authenticationisrequiredwhenthesecurityconstraints(ifany)thatcontaintheurl-patternthatisthebestmatchfortherequestURIcombinetoimposeanauth-constraint(namingroles)ontheHTTPmethodoftherequest.
Similarly,aprotectedtransportisnotrequiredunlessthesecurityconstraintsthatapplytotherequestcombinetoimposeauser-data-constraint(withaprotectedtransport-guarantee)ontheHTTPmethodoftherequest.
Chapter13Security15113.
10LoginandLogoutThecontainerestablishesthecalleridentityofarequestpriortodispatchingtherequesttotheservletengine.
Thecalleridentityremainsunchangedthroughouttheprocessingoftherequestoruntiltheapplicationsucessfullycallsauthenticate,loginorlogoutontherequest.
Forasynchronousrequests,thecalleridentityestablishedattheinitialdispatchremainsunchangeduntiltheprocessingoftheoverallrequestcompletes,ortheapplicationsuccessfullycallsauthenticate,loginorlogoutontherequest.
Beingloggedintoanapplicationduringtheprocessingofarequest,correspondspreciselytotherebeingavalidnon-nullcalleridentityassociatedwiththerequestasmaybedeterminedbycallinggetRemoteUserorgetUserPrincipalontherequest.
Anullreturnvaluefromeitherofthesemethodsindicatesthatthecallerisnotloggedintotheapplicationwithrespecttotheprocessingoftherequest.
ContainersmaycreateHTTPSessionobjectstotrackloginstate.
Ifadevelopercreatesasessionwhileauserisnotauthenticated,andthecontainerthenauthenticatestheuser,thesessionvisibletodevelopercodeafterloginmustbethesamesessionobjectthatwascreatedpriortologinoccurringsothatthereisnolossofsessioninformation.
152JavaServletSpecification153CHAPTER14DeploymentDescriptorThischapterspecifiestheJavaServletSpecificationversion3.
0requirementsforWebcontainersupportofdeploymentdescriptors.
ThedeploymentdescriptorconveystheelementsandconfigurationinformationofaWebapplicationbetweenApplicationDevelopers,ApplicationAssemblers,andDeployers.
ForJavaServletsv.
2.
4andgreater,thedeploymentdescriptorisdefinedintermsofanXMLschemadocument.
Forbackwardscompatibilityofapplicationswrittentothe2.
2versionoftheAPI,Webcontainersarealsorequiredtosupportthe2.
2versionofthedeploymentdescriptor.
Forbackwardscompatibilityofapplicationswrittentothe2.
3versionoftheAPI,Webcontainersarealsorequiredtosupportthe2.
3versionofthedeploymentdescriptor.
The2.
2versionisavailableathttp://java.
sun.
com/j2ee/dtds/web-app_2_2.
dtdand2.
3versionisavailableathttp://java.
sun.
com/dtd/web-app_2_3.
dtd.
14.
1DeploymentDescriptorElementsThefollowingtypesofconfigurationanddeploymentinformationarerequiredtobesupportedintheWebapplicationdeploymentdescriptorforallservletcontainers:ServletContextInitParametersSessionConfigurationServletDeclarationServletMappingsApplicationLifecyleListenerclassesFilterDefinitionsandFilterMappingsMIMETypeMappingsWelcomeFilelistErrorPagesLocaleandEncodingMappings154JavaServletSpecificationSecurityconfiguration,includinglogin-config,security-constraint,security-role,security-role-refandrun-as14.
2RulesforProcessingtheDeploymentDescriptorThissectionlistssomegeneralrulesthatWebcontainersanddevelopersmustnoteconcerningtheprocessingofthedeploymentdescriptorforaWebapplication.
Webcontainersmustremoveallleadingandtrailingwhitespace,whichisdefinedas"S(whitespace)"inXML1.
0(http://www.
w3.
org/TR/2000/WD-xml-2e-20000814),fortheelementcontentofthetextnodesofadeploymentdescriptor.
Thedeploymentdescriptormustbevalidagainsttheschema.
WebcontainersandtoolsthatmanipulateWebapplicationshaveawiderangeofoptionsforcheckingthevalidityofaWAR.
Thisincludescheckingthevalidityofthedeploymentdescriptordocumentheldwithin.
Additionally,itisrecommendedthatWebcontainersandtoolsthatmanipulateWebapplicationsprovidealevelofsemanticchecking.
Forexample,itshouldbecheckedthatarolereferencedinasecurityconstrainthasthesamenameasoneofthesecurityrolesdefinedinthedeploymentdescriptor.
Incasesofnon-conformantWebapplications,toolsandcontainersshouldinformthedeveloperwithdescriptiveerrormessages.
High-endapplicationservervendorsareencouragedtosupplythiskindofvaliditycheckingintheformofatoolseparatefromthecontainer.
Thesubelementsunderweb-appcanbeinanarbitraryorderinthisversionofthespecification.
BecauseoftherestrictionofXMLSchema,Themultiplicityoftheelementsdistributable,session-config,welcome-file-list,jsp-config,login-config,andlocale-encoding-mapping-listwaschangedfrom"optional"to"0ormore".
Thecontainersmustinformthedeveloperwithadescriptiveerrormessagewhenthedeploymentdescriptorcontainsmorethanoneelementofsession-config,jsp-config,andlogin-config.
Thecontainermustconcatenatetheitemsinwelcome-file-listandlocale-encoding-mapping-listwhentherearemultipleoccurrences.
Themultipleoccurrenceofdistributablemustbetreatedexactlyinthesamewayasthesingleoccurrenceofdistributable.
URIpathsspecifiedinthedeploymentdescriptorareassumedtobeinURL-decodedform.
ThecontainersmustinformthedeveloperwithadescriptiveerrormessagewhenURLcontainsCR(#xD)orLF(#xA).
ThecontainersmustpreserveallothercharactersincludingwhitespaceinURL.
Chapter14DeploymentDescriptor155Containersmustattempttocanonicalizepathsinthedeploymentdescriptor.
Forexample,pathsoftheform/a/.
.
/bmustbeinterpretedas/b.
Pathsbeginningorresolvingtopathsthatbeginwith.
.
/arenotvalidpathsinthedeploymentdescriptor.
URIpathsreferringtoaresourcerelativetotherootoftheWAR,orapathmappingrelativetotherootoftheWAR,unlessotherwisespecified,shouldbeginwithaleading/.
Inelementswhosevalueisanenumeratedtype,thevalueiscasesensitive.
14.
3DeploymentDescriptorThedeploymentdescriptorforthisrevisionofthespecificationisavailableathttp://java.
sun.
com/xml/ns/javaee/web-app_3_0.
xsd14.
4DeploymentDescriptorDiagramThissectionillustratestheelementsindeploymentdescriptor.
Attributesarenotshowninthediagrams.
SeeDeploymentDescriptorSchemaforthedetailedinformation.
1.
web-appElement156JavaServletSpecificationTheweb-appelementistherootdeploymentdescriptorforaWebapplication.
Thiselementcontainsthefollowingelements.
Thiselementhasarequiredattributeversiontospecifytowhichversionoftheschemathedeploymentdescriptorconforms.
Allsubelementsunderthiselementcanbeinanarbitraryorder.
FIGURE14-1web-appElementStructureChapter14DeploymentDescriptor1572.
descriptionElementThedescriptionelementistoprovideatextdescribingtheparentelement.
Thiselementoccursnotonlyundertheweb-appelementbutalsounderothermultipleelements.
Ithasanoptionalattributexml:langtoindicatewhichlanguageisusedinthedescription.
ThedefaultvalueofthisattributeisEnglish("en").
3.
display-nameElementThedisplay-namecontainsashortnamethatisintendedtobedisplayedbytools.
Thedisplaynameneednottobeunique.
Thiselementhasanoptionalattributexml:langtospecifythelanguage.
4.
iconElementTheiconcontainssmall-iconandlarge-iconelementsthatspecifythefilenamesforsmallandlargeGIForJPEGiconimagesusedtorepresenttheparentelementinaGUItool.
5.
distributableElementThedistributableindicatesthatthisWebapplicationisprogrammedappropriatelytobedeployedintoadistributedservletcontainer.
6.
context-paramElementThecontext-paramcontainsthedeclarationofaWebapplication'sservletcontextinitializationparameters.
7.
filterElementThefilterdeclaresafilterintheWebapplication.
ThefilterismappedtoeitheraservletoraURLpatterninthefilter-mappingelement,usingthefilter-namevaluetoreference.
FilterscanaccesstheinitializationparametersdeclaredinthedeploymentdescriptoratruntimeviatheFilterConfiginterface.
Thefilter-nameelementisthelogicalnameofthefilter.
ItmustbeuniquewithintheWebapplication.
Theelementcontentoffilter-nameelementmustnotbeempty.
Thefilter-classisthefullyqualifiedclassnameofthefilter.
The158JavaServletSpecificationinit-paramelementcontainsname-valuepairasaninitializationparameterofthisfilter.
Theoptionalasync-supportedelement,whenspecified,indicatesthatthefiltersupportsasynchronousrequestprocessing.
FIGURE14-2filterElementStructure8.
filter-mappingElementChapter14DeploymentDescriptor159Thefilter-mappingisusedbythecontainertodecidewhichfilterstoapplytoarequestinwhatorder.
Thevalueofthefilter-namemustbeoneofthefilterdeclarationsinthedeploymentdescriptor.
Thematchingrequestcanbespecifiedeitherurl-patternorservlet-name.
FIGURE14-3filter-mappingElementStructure9.
listenerElementThelistenerindicatesthedeploymentpropertiesforanapplicationlistenerbean.
Thesub-elementlistener-classdeclaresthataclassintheapplicationmustberegisteredasaWebapplicationlistenerbean.
Thevalueisthefullyqualifiedclassnameofthelistenerclass.
FIGURE14-4listenerElementStructure160JavaServletSpecification10.
servletElementTheservletisusedtodeclareaservlet.
Itcontainsthedeclarativedataofaservlet.
Thejsp-fileelementcontainsthefullpathtoaJSPfilewithinthewebapplicationbeginningwitha"/".
Ifajsp-fileisspecifiedandtheload-on-startupelementispresent,thentheJSPshouldbeprecompiledandloaded.
Theservlet-nameelementcontainsthecanonicalnameoftheservlet.
Eachservletnameisuniquewithinthewebapplication.
Theelementcontentofservlet-namemustnotbeempty.
Theservlet-classcontainsthefullyqualifiedclassnameoftheservlet.
Therun-aselementspecifiestheidentitytobeusedfortheexecutionofacomponent.
Itcontainsanoptionaldescription,andthenameofasecurityrolespecifiedbytherole-nameelement.
Theelementload-on-startupindicatesthatthisservletshouldbeloaded(instantiatedandhaveitsinit()called)onthestartupoftheWebapplication.
Theelementcontentofthiselementmustbeanintegerindicatingtheorderinwhichtheservletshouldbeloaded.
Ifthevalueisanegativeinteger,ortheelementisnotpresent,thecontainerisfreetoloadtheservletwheneveritchooses.
Ifthevalueisapositiveintegeror0,thecontainermustloadandinitializetheservletastheapplicationisdeployed.
Thecontainermustguaranteethatservletsmarkedwithlowerintegersareloadedbeforeservletsmarkedwithhigherintegers.
Thecontainermaychoosetheorderofloadingofservletswiththesameload-on-startupvalue.
Thesecurity-role-refelementdeclaresthesecurityrolereferenceinacomponent'sorinadeploymentcomponent'scode.
Itconsistsofanoptionaldescription,thesecurityrolenameusedinthecode(role-name),andanoptionallinktoasecurityrole(role-link).
Ifthesecurityroleisnotspecified,thedeployermustchooseanappropriatesecurityrole.
Theoptionalasync-supportedelement,whenspecified,indicatesthattheServletcansupportasynchronousrequestprocessing.
Ifaservletsupportsfileuploadfunctionalityandprocessingofmime-multipartrequests,theconfigurationforthesamecanbeprovidedviathemultipart-configelementinthedescriptor.
TheChapter14DeploymentDescriptor161multipart-configelementcanbeusedtospecifythelocationwherethefilescanbestored,maximumsizeofthefilebeinguploaded,maximumrequestsizeandthesizethresholdafterwhichthefilewillbewrittentothedisk.
FIGURE14-5servletElementStructure162JavaServletSpecification11.
servlet-mappingElementTheservlet-mappingdefinesamappingbetweenaservletandaURLpattern.
FIGURE14-6servlet-mappingElementStructure12.
session-configElementThesession-configdefinesthesessionparametersforthisWebapplication.
Thesub-elementsession-timeoutdefinesthedefaultsessiontimeoutintervalforallsessionscreatedinthisWebapplication.
Thespecifiedtimeoutmustbeexpressedinawholenumberofminutes.
Ifthetimeoutis0orless,thecontainerensuresthedefaultbehaviorofsessionsisnevertotimeout.
Ifthiselementisnotspecified,thecontainermustsetitsdefaulttimeoutperiod.
FIGURE14-7session-configElementStructure13.
mime-mappingElementChapter14DeploymentDescriptor163Themime-mappingdefinesamappingbetweenanextensionandamimetype.
Theextensionelementcontainsastringdescribinganextension,suchas"txt".
FIGURE14-8mime-mappingElementStructure14.
welcome-file-listElementThewelcome-file-listcontainsanorderedlistofwelcomefiles.
Thesub-elementwelcome-filecontainsafilenametouseasadefaultwelcomefile,suchasindex.
htmlFIGURE14-9welcome-file-listElementStructure15.
error-pageElementTheerror-pagecontainsamappingbetweenanerrorcodeoranexceptiontypetothepathofaresourceintheWebapplication.
However,theerror-codeortheexception-typeelementcanbeomittedtospecifyadefaulterrorpage.
Thesub-elementexception-typecontainsafullyqualifiedclassnameofaJava164JavaServletSpecificationexceptiontype.
Thesub-elementlocationelementcontainsthelocationoftheresourceinthewebapplicationrelativetotherootofthewebapplication.
Thevalueofthelocationmusthavealeading'/'.
FIGURE14-10error-pageElementStructure16.
jsp-configElementThejsp-configisusedtoprovideglobalconfigurationinformationfortheJSPfilesinawebapplication.
Ithastwosub-elements,taglibandjsp-property-group.
ThetaglibelementcanbeusedtoprovideinformationonataglibrarythatisusedbyaJSPpagewithintheWebapplication.
SeeJavaServerPagesspecificationversion2.
1fordetail.
FIGURE14-11jsp-configElementStructureChapter14DeploymentDescriptor16517.
security-constraintElementThesecurity-constraintisusedtoassociatesecurityconstraintswithoneormorewebresourcecollections.
Thesub-elementweb-resource-collectionindentifiesasubsetoftheresourcesandHTTPmethodsonthoseresourceswithinaWebapplicationtowhichasecurityconstraintapplies.
Theauth-constraintindicatestheuserrolesthatshouldbepermittedaccesstothisresourcecollection.
Therole-nameusedheremusteithercorrespondtotherole-nameofoneofthesecurity-roleelementsdefinedforthisWebapplication,orbethespeciallyreservedrole-name"*"thatisacompactsyntaxforindicatingallrolesinthewebapplication.
Ifboth"*"androlenamesappear,thecontainerinterpretsthisasallroles.
Ifnorolesaredefined,nouserisallowedaccesstotheportionoftheWebapplicationdescribedbythecontainingsecurity-constraint.
Thecontainermatchesrolenamescasesensitivelywhendeterminingaccess.
Theuser-data-constraintindicateshowdatacommunicatedbetweentheclient166JavaServletSpecificationandcontainershouldbeprotectedbythesub-elementtransport-guarantee.
Thelegalvaluesofthetransport-guaranteeiseitheroneofNONE,INTEGRAL,orCONFIDENTIAL.
FIGURE14-12security-constraintElementStructure18.
login-configElementThelogin-configisusedtoconfiguretheauthenticationmethodthatshouldbeused,therealmnamethatshouldbeusedforthisapplication,andtheattributesthatareneededbytheformloginmechanism.
Thesub-elementauth-methodconfigurestheauthenticationmechanismfortheWebapplication.
TheelementcontentmustbeeitherBASIC,DIGEST,FORM,CLIENT-CERT,oraChapter14DeploymentDescriptor167vendor-specificauthenticationscheme.
Therealm-nameindicatestherealmnametousefortheauthenticationschemechosenfortheWebapplication.
Theform-login-configspecifiestheloginanderrorpagesthatshouldbeusedinFORMbasedlogin.
IfFORMbasedloginisnotused,theseelementsareignored.
FIGURE14-13login-configElementStructure19.
security-roleElementThesecurity-roledefinesasecurityrole.
Thesub-elementrole-namedesignatesthenameofthesecurityrole.
ThenamemustconformtothelexicalrulesforNMTOKEN.
FIGURE14-14security-roleElementStructure20.
env-entryElementTheenv-entrydeclaresanapplication'senvironmententry.
Thesub-elementenv-entry-namecontainsthenameofadeploymentcomponent'senvironmententry.
ThenameisaJNDInamerelativetothejava:comp/envcontext.
Thenamemustbeuniquewithinadeploymentcomponent.
Theenv-entry-typecontainsthefully-qualifiedJavatypeoftheenvironmententryvaluethatis168JavaServletSpecificationexpectedbytheapplication'scode.
Thesub-elementenv-entry-valuedesignatesthevalueofadeploymentcomponent'senvironmententry.
ThevaluemustbeaStringthatisvalidfortheconstructorofthespecifiedtypethattakesasingleStringasaparameter,orasinglecharacterforjava.
lang.
Character.
Theoptionalinjection-targetelementisusedtodefinetheinjectionofthenamedresourceintofieldsorJavaBeansproperties.
Aninjection-targetspecifiesaclassandanamewithinthatclassintowhicharesourceshouldbeinjected.
Theinjection-target-classspecifiesthefullyqualifiedclassnamethatisthetargetoftheinjection.
Theinjection-target-namespecifiesthetargetwithinthespecifiedclass.
ThetargetisfirstlookedforasaJavaBeanpropertyname.
Ifnotfound,thetargetislookedforasafieldname.
ThespecifiedresourcewillbeinjectedintothetargetduringinitializationoftheclassbyeithercallingthesetmethodforthetargetpropertyorbysettingavalueintothenameChapter14DeploymentDescriptor169filed.
Ifaninjection-targetisspecifiedfortheenvironmententry,theenv-entry-typemaybeommittedorMUSTmatchthetypeoftheinjectiontarget.
Ifnoinjection-targetisspecified,theenv-entry-typeisrequired.
FIGURE14-15env-entryElementStructure21.
ejb-refElementTheejb-refdeclaresthereferencetoanenterprisebean'shome.
Theejb-ref-namespecifiesthenameusedinthecodeofthedeploymentcomponentthatisreferencingtheenterprisebean.
Theejb-ref-typeistheexpectedtypeofthereferencedenterprisebean,whichiseitherEntityorSession.
Thehomedefinesthefullyqualifiednameofthereferencedenterprisebean'shomeinterface.
Theremotedefinesthefullyqualifiednameofthereferencedenterprisebean'sremoteinterface.
Theejb-linkspecifiesthatanEJBreferenceislinkedtothe170JavaServletSpecificationenterprisebean.
SeeJavaPlatform,EnterpriseEdition,version6formoredetail.
Inadditiontotheseelements,theinjection-targetelementcanbeusedtodefineinjectionofthenamedenterprisebeanintoacomponentfieldorproperty.
FIGURE14-16ejb-refElementStructure22.
ejb-local-refElementChapter14DeploymentDescriptor171Theejb-local-refdeclaresthereferencetotheenterprisebean'slocalhome.
Thelocal-homedefinesthefullyqualifiednameoftheenterprisebean'slocalhomeinterface.
Thelocaldefinesthefullyqualifiednameoftheenterprisebean'slocalinterface.
FIGURE14-17ejb-local-refElementStructure23.
service-refElementTheservice-refdeclaresthereferencetoaWebservice.
Theservice-ref-namedeclaresthelogicalnamethatthecomponentsinthemoduleusetolookuptheWebservice.
Itisrecommendedthatallservicereferencenamesstartwith/service/.
Theservice-interfacedefinesthefullyqualifiedclassnameoftheJAX-WSServiceinterfacethattheclientdependson.
Inmostcases,thevaluewillbejavax.
xml.
rpc.
Service.
AJAX-WSgeneratedServiceInterfaceclassmayalsobespecified.
Thewsdl-fileelementcontainstheURIlocationofaWSDLfile.
Thelocationisrelativetotherootofthemodule.
Thejaxrpc-mapping-filecontainsthenameofafilethatdescribestheJAX-WSmappingbetweentheJavainteracesusedbytheapplicationandtheWSDLdescriptioninthewsdl-file.
Thefilenameisarelativepathwithinthemodulefile.
Theservice-172JavaServletSpecificationqnameelementdeclaresthespecificWSDLserviceelementthatisbeingreferredto.
Itisnotspecifiedifnowsdl-fileisdeclared.
Theport-component-refelementdeclaresaclientdependencyonthecontainerforresolvingaServiceEndpointInterfacetoaWSDLport.
ItoptionallyassociatestheServiceEndpointInterfacewithaparticularport-component.
ThisisonlyusedbythecontainerforaService.
getPort(Class)methodcall.
Thehandlerelementdeclaresthehandlerforaport-component.
Handlerscanaccesstheinit-paramname-valuepairsusingtheHandlerInfointerface.
Ifport-nameisnotspecified,thehandlerisassumedtobeassociatedwithallportsoftheservice.
SeeJSR-109Specification[http://www.
jcp.
org/en/jsr/detailid=109]fordetail.
ThecontainerthatisnotapartofaJavaEEimplementationisnotrequiredtosupportthiselement.
FIGURE14-18service-refElementStructureChapter14DeploymentDescriptor17324.
resource-refElementTheresource-refcontainsthedeclarationofadeploymentcomponent'sreferencetotheexternalresource.
Theres-ref-namespecifiesthenameofaresourcemanagerconnectionfactoryreference.
ThenameisaJNDInamerelativetothejava:comp/envcontext.
Thenamemustbeuniquewithinadeploymentfile.
Theres-typeelementspecifiesthetypeofthedatasource.
ThetypeisthefullyqualifiedJavalanguageclassortheinterfaceexpectedtobeimplementedbythedatasource.
Theres-authspecifieswhetherthedeploymentcomponentcodesignsonprogrammaticallytotheresourcemanager,orwhetherthecontainerwillsignontotheresourcemanageronbehalfofthedeploymentcomponent.
Inthelattercase,thecontainerusestheinformationsuppliedbythedeployer.
Theres-sharing-scopespecifieswhetherconnectionsobtainedthroughthegivenresourcemanagerconnectionfactoryreferencecanbeshared.
Thevalue,ifspecified,mustbeeitherShareableorUnshareable.
Theoptionalinjection-targetelementisusedtodefineinjectionofthenamedresourceintofieldsorJavaBeansproperties.
FIGURE14-19resource-refElementStructure174JavaServletSpecification25.
resource-env-refElementTheresource-env-refcontainsthedeploymentcomponent'sreferencetotheadministeredobjectassociatedwitharesourceinthedeploymentcomponent'senvironment.
Theresource-env-ref-namespecifiesthenameoftheresourceenvironmentreference.
ThevalueistheenvironmententrynameusedinthedeploymentcomponentcodeandisaJNDInamerelativetothejava:comp/envcontextandmustbeuniquewithinthedeploymentcomponent.
Theresource-env-ref-typespecifiesthetypeoftheresourceenvironmentreference.
ItisthefullyqualifiednameofaJavalanguageclassortheinterface.
Theoptionalinjection-targetelementisusedtodefineinjectionofthenamedresourceintofieldsorJavaBeansproperties.
Theresource-env-ref-typeMUSTbesuppliedunlessaninjectiontargetisspecified,inwhichcasethetypeofthetargetisused.
Ifbotharespecified,thetypeMUSTbeassignmentcompatiblewiththetypeoftheinjectiontarget.
FIGURE14-20resource-env-refElementStructure26.
message-destination-refElementThemessage-destination-refelementcontainsadeclarationofdeploymentcomponent'sreferencetoamessagedestinationassociatedwitharesourceindeploymentcomponent'senvironment.
Themessage-destination-ref-nameelementspecifiesthenameofamessagedestinationreference;itsvalueistheenvironmententrynameusedindeploymentcomponentcode.
ThenameisaChapter14DeploymentDescriptor175JNDInamerelativetothejava:comp/envcontextandmustbeuniquewithinanejb-jarforenterprisebeansoradeploymentfileforothers.
Themessage-destination-typespecifiesthetypeofthedestination.
ThetypeisspecifiedbytheJavainterfaceexpectedtobeimplementedbythedestination.
Themessage-destination-usagespecifiestheuseofthemessagedestinationindicatedbythereference.
Thevalueindicateswhethermessagesareconsumedfromthemessagedestination,producedforthedestination,orboth.
TheAssemblermakesuseofthisinformationinlinkingproducersofadestinationwithitsconsumers.
Themessage-destination-linklinksamessagedestinationreferenceormessage-drivenbeantoamessagedestination.
TheAssemblersetsthevaluetoreflecttheflowofmessagesbetweenproducersandconsumersintheapplication.
Thevaluemustbethemessage-destination-nameofamessagedestinationinthesamedeploymentfileorinanotherdeploymentfileinthesameJavaEEapplicationunit.
Alternatively,thevaluemaybecomposedofapathnamespecifyingadeploymentfilecontainingthereferencedmessagedestinationwiththemessage-destination-nameofthedestinationappendedandseparatedfromthepathnameby"#".
Thepathnameisrelativetothedeploymentfilecontainingdeploymentcomponentthatisreferencingthemessagedestination.
Thisallowsmultiplemessagedestinationswiththesamenametobeuniquelyidentified.
Theoptionalinjection-targetelementisusedtodefineinjectionofthenamedresourceintofieldsorJavaBeansproperties.
Themessage-destination-typeMUSTbespecifiedunlessaninjectiontargetisspecified,inwhichcasethetypeofthetargetisused.
Ifbotharespecified,thetypeMUSTbeassignmentcompatiblewiththetypeoftheinjectiontarget.
176JavaServletSpecificationExample:FIGURE14-21message-destination-refElementStructurejms/StockQueuejavax.
jms.
QueueConsumesCorporateStocksChapter14DeploymentDescriptor17727.
message-destinationElementThemessage-destinationspecifiesamessagedestination.
Thelogicaldestinationdescribedbythiselementismappedtoaphysicaldestinationbythedeployer.
Themessage-destination-nameelementspecifiesanameforamessagedestination.
Thisnamemustbeuniqueamongthenamesofmessagedestinationswithinthedeploymentfile.
Example:FIGURE14-22message-destinationElementStructure28.
locale-encoding-mapping-listElementThelocale-encoding-mapping-listcontainsthemappingbetweenthelocaleandtheencoding.
specifiedbythesub-elementlocale-encoding-mapping.
CorporateStocks178JavaServletSpecificationExample:FIGURE14-23locale-encoding-mapping-listElementStructure14.
5ExamplesThefollowingexamplesillustratetheusageofthedefinitionslistedinthedeploymentdescriptorschema.
jaShift_JISChapter14DeploymentDescriptor17914.
5.
1ABasicExampleCODEEXAMPLE14-1BasicDeploymentDescriptorExampleASimpleApplicationWebmasterwebmaster@mycorp.
comcatalogcom.
mycorp.
CatalogServletcatalogSpringcatalog/catalog/*30pdfapplication/pdfindex.
jspindex.
htmlindex.
htm404/404.
html180JavaServletSpecification14.
5.
2AnExampleofSecurityCODEEXAMPLE14-2DeploymentDescriptorExampleUsingSecurityASecureApplicationcatalogcom.
mycorp.
CatalogServletcatalogSpringMGRmanagermanagercatalog/catalog/*SalesInfo/salesinfo/*GETPOSTmanagerCONFIDENTIALChapter14DeploymentDescriptor181CODEEXAMPLE14-2DeploymentDescriptorExampleUsingSecurity182JavaServletSpecification183CHAPTER15RequirementsrelatedtootherSpecificationsThischapterliststherequirementsforwebcontainersthatareincludedinproductsthatalsoincludeotherJavatechnologies.
InthefollowingsectionsanyreferencetoJavaEEappliestonotonlythefullJavaEEprofilebutalsoanyprofilethatincludessupportforServlet,liketheJavaEEWebProfile.
FormoreinformationonprofilespleaserefertotheJavaEEplatformspecification.
15.
1SessionsDistributedservletcontainersthatarepartofaJavaEEimplementationmustsupportthemechanismnecessaryformigratingotherJavaEEobjectsfromoneJVMtoanother.
15.
2WebApplications15.
2.
1WebApplicationClassLoaderServletcontainersthatarepartofaJavaEEproductshouldnotallowtheapplicationtooverrideJavaSEorJavaEEplatformclasses,suchasthoseinjava.
*andjavax.
*namespaces,thateitherJavaSEorJavaEEdonotallowtobemodified.
184JavaServletSpecification15.
2.
2WebApplicationEnvironmentJavaEEdefinesanamingenvironmentthatallowsapplicationstoeasilyaccessresourcesandexternalinformationwithoutexplicitknowledgeofhowtheexternalinformationisnamedororganized.
AsservletsareanintegralcomponenttypeofJavaEEtechnology,provisionhasbeenmadeintheWebapplicationdeploymentdescriptorforspecifyinginformationallowingaservlettoobtainreferencestoresourcesandenterprisebeans.
Thedeploymentelementsthatcontainthisinformationare:env-entryejb-refejb-local-refresource-refresource-env-refservice-refmessage-destination-refpersistence-context-refpersistence-unit-refThedeveloperusestheseelementstodescribecertainobjectsthattheWebapplicationrequirestoberegisteredintheJNDInamespaceintheWebcontaineratruntime.
TherequirementsoftheJavaEEenvironmentwithregardtosettinguptheenvironmentaredescribedinChapter5oftheJavaEESpecification.
ServletcontainersthatarepartofaJavaEEtechnology-compliantimplementationarerequiredtosupportthissyntax.
ConsulttheJavaEESpecificationformoredetails.
Thistypeofservletcontainermustsupportlookupsofsuchobjectsandcallsmadetothoseobjectswhenperformedonathreadmanagedbytheservletcontainer.
Thistypeofservletcontainershouldsupportthisbehaviorwhenperformedonthreadscreatedbythedeveloper,butarenotcurrentlyrequiredtodoso.
Sucharequirementwillbeaddedinthenextversionofthisspecification.
Developersarecautionedthatdependingonthiscapabilityforapplication-createdthreadsisnotrecommended,asitisnon-portable.
15.
2.
3JNDINameforWebModuleContextRootURLTheJavaEEPlatformSpecificationdefinesastandardizedglobalJNDInamespaceandaseriesofrelatednamespacesthatmaptovariousscopesofaJavaEEapplication.
Thesenamespacescanbeusedbyapplicationstoportablyretrievereferencestocomponentsandresources.
ThissectiondefinestheJNDInamesbywhichthebaseurlforawebapplicationisrequiredtoberegistered.
Chapter15RequirementsrelatedtootherSpecifications185Thenameofthepre-definedjava.
net.
URLresourceforthecontextrootofawebapplicationhasthefollowingsyntax:java:global[/]/!
ROOTintheglobalnamespaceandjava:app/!
ROOTintheapplication-specificnamespace.
PleseseesectionEE8.
1.
1(Componentcreation)andEE8.
1.
2(Applicationassembly)fortherulestodeterminetheappnameandmodulenameTheisapplicableonlywhenthewebappispackagedwithina.
earfile.
Thejava:appprefixallowsacomponentexecutingwithinaJavaEEapplicationtoaccessanapplication-specificnamespace.
Thejava:appnameallowsamoduleinanenterpriseapplicationtoreferencethecontextrootofanothermoduleinthesameenterpriseapplication.
Theisarequiredpartofthesyntaxforjava:appurl.
ExamplesTheaboveURLcanthenbeusedwithinanapplicationasfollows:Ifawebapplicationisdeployedstandalonewithmodule-nameasmyWebApp.
TheURLcanthenbeinjectedintoanotherwebmoduleasfollows:CODEEXAMPLE15-1@Resource(lookup="java:global/myWebApp!
ROOT")URLmyWebApp;WhenpackagedinanearfilenamedmyAppitcanbeusedasfollows:CODEEXAMPLE15-2@Resource(lookup="java:global/myApp/myWebApp!
ROOT")URLmyWebApp;15.
3SecurityThissectiondetailstheadditionalsecurityrequirementsforwebcontainerswhenincludedinaproductthatalsocontainsEJB,JACCandorJASPIC.
Thefollowingsectionscallouttherequirements186JavaServletSpecification15.
3.
1PropagationofSecurityIdentityinEJBCallsAsecurityidentity,orprincipal,mustalwaysbeprovidedforuseinacalltoanenterprisebean.
ThedefaultmodeincallstoenterprisebeansfromwebapplicationsisforthesecurityidentityofawebusertobepropagatedtotheEJBcontainer.
Inotherscenarios,webcontainersarerequiredtoallowwebusersthatarenotknowntothewebcontainerortotheEJBcontainertomakecalls:Webcontainersarerequiredtosupportaccesstowebresourcesbyclientsthathavenotauthenticatedthemselvestothecontainer.
ThisisthecommonmodeofaccesstowebresourcesontheInternet.
Applicationcodemaybethesoleprocessorofsignonandcustomizationofdatabasedoncalleridentity.
Inthesescenarios,awebapplicationdeploymentdescriptormayspecifyarun-aselement.
Whenarun-asroleisspecifiedforaServlet,theServletcontainermustpropagateaprincipalmappedtotheroleasthesecurityidentityinanycallfromtheServlettoanEJBs,includingcallsoriginatingfromtheServlet'sinitanddestroymethods.
Thesecurityrolenamemustbeoneofthesecurityrolenamesdefinedforthewebapplication.
ForwebcontainersrunningaspartofaJavaEEplatform,theuseofrun-aselementsmustbesupportedbothforcallstoEJBcomponentswithinthesameJavaEEapplication,andforcallstoEJBcomponentsdeployedinotherJavaEEapplications.
15.
3.
2ContainerAuthorizationRequirementsInaJavaEEproductorinaproductthatincludessupportforJavaAuthorizationContractsforContainers(JACC,i.
e,JSR115),allServletcontainersMUSTimplementsupportforJACC.
TheJACCSpecificationisavailablefordownloadathttp://www.
jcp.
org/en/jsr/detailid=11515.
3.
3ContainerAuthenticationRequirementsInaJavaEEproduct,oraproductthatincludessupportforTheJavaAuthenticationSPIforContainers(JASPIC,i.
e,JSR196),allServletcontainersMUSTimplementtheServletContainerProfileoftheJASPICspecification.
TheJASPICSpecificationisavailablefordownloadathttp://www.
jcp.
org/en/jsr/detailid=196Chapter15RequirementsrelatedtootherSpecifications18715.
4DeploymentThissectiondetailsthedeploymentdescriptor,packaginganddeploymentdescriptorprocessingrequirementsofaJavaEEtechnologycompliantcontainerandproductsthatincludesupportforJSPandorWebServices.
15.
4.
1DeploymentDescriptorElementsThefollowingadditionalelementsexistintheWebapplicationdeploymentdescriptortomeettherequirementsofWebcontainersthatareJSPpagesenabledorpartofaJavaEEapplicationserver.
Theyarenotrequiredtobesupportedbycontainerswishingtosupportonlytheservletspecification:jsp-configSyntaxfordeclaringresourcereferences(env-entry,ejb-ref,ejb-local-ref,resource-ref,resource-env-ref)Syntaxforspecifyingthemessagedestination(message-destination,message-destination-ref)ReferencetoaWebservice(service-ref)ReferencetoaPersistencecontext(persistence-context-ref)ReferencetoaPersistenceUnit(persistence-unit-ref)ThesyntaxfortheseelementsisnowheldintheJavaServerPagesspecificationversion2.
2,andtheJavaEEspecification.
15.
4.
2PackagingandDeploymentofJAX-WSComponentsWebcontainersmaychoosetosupportrunningcomponentswrittentoimplementaWebserviceendpointasdefinedbytheJAX-RPCand/orJAX-WSspecifications.
WebcontainersembeddedinaJavaEEconformantimplementationarerequiredtosupportJAX-RPCandJAX-WSwebservicecomponents.
ThissectiondescribesthepackaginganddeploymentmodelforwebcontainerswhenincludedinaproductwhichalsosupportsJAX-RPCandJAX-WS.
JSR-109[http://jcp.
org/jsr/detail/109.
jsp]definesthemodelforpackagingaWebserviceinterfacewithitsassociatedWSDLdescriptionandassociatedclasses.
ItdefinesamechanismforJAX-WSandJAX-RPCenabledWebcontainerstolinktoacomponentthatimplementsthisWebservice.
AJAX-WSorJAX-RPCWebserviceimplementationcomponentusestheAPIsdefinedbytheJAX-WSand/orJAX-RPC188JavaServletSpecificationspecifications,whichdefinesitscontractwiththeJAX-WSand/orJAX-RPCenabledWebcontainers.
ItispackagedintotheWARfile.
TheWebservicedevelopermakesadeclarationofthiscomponentusingtheusualdeclaration.
JAX-WSandJAX-RPCenabledWebcontainersmustsupportthedeveloperinusingtheWebdeploymentdescriptortodefinethefollowinginformationfortheendpointimplementationcomponent,usingthesamesyntaxasforHTTPServletcomponentsusingtheservletelement.
Thechildelementsareusedtospecifyendpointinformationinthefollowingway:theservlet-nameelementdefinesalogicalnamewhichmaybeusedtolocatethisendpointdescriptionamongtheotherWebcomponentsintheWARtheservlet-classelementprovidesthefullyqualifiedJavaclassnameofthisendpointimplementationthedescriptionelement(s)maybeusedtodescribethecomponentandmaybedisplayedinatooltheload-on-startupelementspecifiestheorderinwhichthecomponentisinitializedrelativetootherWebcomponentsintheWebcontainerthesecurity-role-refelementmaybeusedtotestwhethertheauthenticateduserisinalogicalsecurityroletherun-aselementmaybeusedtooverridetheidentitypropagatedtoEJBscalledbythiscomponentAnyservletinitializationparametersdefinedbythedeveloperforthisWebcomponentmaybeignoredbythecontainer.
Additionally,theJAX-WSandJAX-RPCenabledWebcomponentinheritsthetraditionalWebcomponentmechanismsfordefiningthefollowinginformation:mappingofthecomponenttotheWebcontainer'sURLnamespaceusingtheservletmappingtechniqueauthorizationconstraintsonWebcomponentsusingsecurityconstraintstheabilitytouseservletfilterstoprovidelow-levelbytestreamsupportformanipulatingJAX-WSand/orJAX-RPCmessagesusingthefiltermappingtechniquethetimeoutcharacteristicsofanyHTTPsessionsthatareassociatedwiththecomponentlinkstoJavaEEobjectsstoredintheJNDInamespaceAlloftheaboverequirementscanbemetusingthepluggabilitymechanismdefinedinSection8.
2,"Pluggability"onpage8-71.
Chapter15RequirementsrelatedtootherSpecifications18915.
4.
3RulesforProcessingtheDeploymentDescriptorThecontainersandtoolsthatarepartofJavaEEtechnology-compliantimplementationarerequiredtovalidatethedeploymentdescriptoragainsttheXMLschemaforstructuralcorrectness.
Thevalidationisrecommended,butnotrequiredforthewebcontainersandtoolsthatarenotpartofaJavaEEtechnologycompliantimplementation.
15.
5AnnotationsandResourceInjectionTheJavaMetadataspecification(JSR-175),whichispartofJ2SE5.
0andgreater,providesameansofspecifyingconfigurationdatainJavacode.
MetadatainJavacodeisalsoreferredtoasannotations.
InJavaEE,annotationsareusedtodeclaredependenciesonexternalresourcesandconfigurationdatainJavacodewithouttheneedtodefinethatdatainaconfigurationfile.
ThissectiondescribesthebehaviorofannotationsandresourceinjectioninJavaEEtechnologycompliantServletcontainers.
ThissectionexpandsontheJavaEEspecificationsection5titled"Resources,Naming,andInjection.
"AnnotationsmustbesupportedonthefollowingcontainermanagedclassesthatimplementthefollowinginterfacesandaredeclaredinthewebapplicationdeploymentdescriptororusingtheannotationsdefinedinSection8.
1,"Annotationsandpluggability"onpage8-67oraddedprogrammatically.
WebcontainersarenotrequiredtoperformresourceinjectionforannotationsoccurringinclassesotherthanthoselistedaboveinTABLE15-1.
TABLE15-1ComponentsandInterfacessupportingAnnotationsandDependencyInjectionComponentTypeClassesimplementingthefollowinginterfacesServletsjavax.
servlet.
ServletFiltersjavax.
servlet.
FilterListenersjavax.
servlet.
ServletContextListenerjavax.
servlet.
ServletContextAttributeListenerjavax.
servlet.
ServletRequestListenerjavax.
servlet.
ServletRequestAttributeListenerjavax.
servlet.
http.
HttpSessionListenerjavax.
servlet.
http.
HttpSessionAttributeListenerjavax.
servlet.
http.
HttpSessionIdListenerjavax.
servlet.
AsyncListener190JavaServletSpecificationReferencesmustbeinjectedpriortoanylifecyclemethodsbeingcalledandthecomponentinstancebeingmadeavailabletheapplication.
Inawebapplication,classesusingresourceinjectionwillhavetheirannotationsprocessedonlyiftheyarelocatedintheWEB-INF/classesdirectory,oriftheyarepackagedinajarfilelocatedinWEB-INF/lib.
Containersmayoptionallyprocessresourceinjectionannotationsforclassesfoundelsewhereintheapplication'sclasspath.
Thewebapplicationdeploymentdescriptorcontainsametadata-completeattributeontheweb-appelement.
Themetadata-completeattributedefineswhethertheweb.
xmldescriptoriscomplete,orwhetherothersourcesofmetadatausedbythedeploymentprocessshouldbeconsidered.
Metadatamaycomefromtheweb.
xmlfile,web-fragment.
xmlfiles,annotationsonclassfilesinWEB-INF/classes,andannotationsonclassesinjarfilesintheWEB-INF/libdirectory.
Ifmetadata-completeissetto"true",thedeploymenttoolonlyexaminestheweb.
xmlfileandmustignoreannotationssuchas@WebServlet,@WebFilter,and@WebListenerpresentintheclassfilesoftheapplication,andmustalsoignoreanyweb-fragment.
xmldescriptorpackagedinajarfileinWEB-INF/lib.
Ifthemetadata-completeattributeisnotspecifiedorissetto"false",thedeploymenttoolmustexaminetheclassfilesandweb-fragment.
xmlfilesformetadata,aspreviouslyspecified.
Theweb-fragment.
xmlalsocontainsthemetadata-completeattributeontheweb-fragmentelement.
Theattributedefineswhethertheweb-fragment.
xmldescriptoriscompleteforthegivenfragment,orwhetheritshouldscanforannotationsintheclassesintheassociatedjarfile.
Ifmetadata-completeissetto"true"thedeploymenttoolonlyexaminestheweb-fragment.
xmlandmustignoreannotationssuchas@WebServlet,@WebFilterand@WebListenerpresentintheclassfilesofthefragment.
Ifmetadata-completeisnotspecifiedorissetto"false"thedeploymenttoolmustexaminetheclassfilesformetadata.
FollowingaretheannotationsthatarerequiredbyaJavaEEtechnologycompliantwebcontainer.
15.
5.
1@DeclareRolesThisannotationisusedtodefinethesecurityrolesthatcomprisethesecuritymodeloftheapplication.
Thisannotationisspecifiedonaclass,anditisusedtodefinerolesthatcouldbetested(i.
e.
,bycallingisUserInRole)fromwithinthemethodsoftheannotatedclass.
Rolesthatareimplicitlydeclaredasaresultoftheiruseina@RolesAllowedneednotbeexplicitlydeclaredusingthe@DeclareRolesannotaion.
The@DeclareRolesannotationmayonlybedefinedinclassesimplementingthejavax.
servlet.
Servletinterfaceorasubclassthereof.
Chapter15RequirementsrelatedtootherSpecifications191Followingisanexampleofhowthisannotationwouldbeused.
Declaring@DeclareRoles("BusinessAdmin")isequivalenttodefiningthefollowingintheweb.
xml.
Thisannotationisnotusedtorelinkapplicationrolestootherroles.
Whensuchlinkingisnecessary,itisaccomplishedbydefininganappropriatesecurity-role-refintheassociateddeploymentdescriptor.
WhenacallismadetoisUserInRolefromtheannotatedclass,thecalleridentityassociatedwiththeinvocationoftheclassistestedformembershipintherolewiththesamenameastheargumenttoisCallerInRole.
Ifasecurity-role-refhasbeendefinedfortheargumentrole-namethecalleristestedformembershipintherolemappedtotherole-name.
Forfurtherdetailsonthe@DeclareRolesannotationrefertotheCommonAnnotationsfortheJavaPlatformspecification(JSR250)section2.
10.
15.
5.
2@EJBAnnotationEnterpriseJavaBeans3.
0(EJB)componentsmaybereferencedfromawebcomponentusingthe@EJBannotation.
The@EJBannotationprovidestheequivalentfunctionalityofdeclaringtheejb-reforejb-local-refelementsinthedeploymentdescriptor.
Fieldsthathaveacorresponding@EJBannotationareinjectedwiththeareferencetothecorrespondingEJBcomponent.
Anexample:@EJBprivateShoppingCartmyCart;CODEEXAMPLE15-3@DeclareRolesAnnotationExample@DeclareRoles("BusinessAdmin")publicclassCalculatorServlet{//.
.
.
}CODEEXAMPLE15-4@DeclareRolesweb.
xmlBusinessAdmin192JavaServletSpecificationInthecaseaboveareferencetotheEJBcomponent"myCart"isinjectedasthevalueoftheprivatefield"myCart"priortotheclasssdeclaringtheinjectionbeingmadeavailable.
Thebehaviorthe@EJBannotationisfurtherdetailedinsection15.
5oftheEJB3.
0specification(JSR220).
15.
5.
3@EJBsAnnotationThe@EJBsannotationallowsmorethanone@EJBannotationstobedeclaredonasingleresource.
Anexample:TheexampleabovetheEJBcomponentsShoppingCartandCalculatoraremadeavailabletoShoppingCartServlet.
TheShoppingCartServletmuststilllookupthereferencesusingJNDIbuttheEJBsdonotneedtodeclaredintheweb.
xmlfile.
The@EJBsannotationisdiscussedinfurtherdetailedinsection15.
5oftheEJB3.
0specification(JSR220).
15.
5.
4@ResourceAnnotationThe@Resourceannotationisusedtodeclareareferencetoaresourcesuchasadatasource,JavaMessagingService(JMS)destination,orenvironmententry.
Thisannotationisequivalenttodeclaringaresource-ref,message-destination-reforenv-ref,orresource-env-refelementinthedeploymentdescriptor.
The@Resourceannotationisspecifiedonaclass,methodorfield.
Thecontainerisresponsibleinjectingreferencestoresourcesdeclaredbythe@ResourceannotationandmappingittotheproperJNDIresources.
SeetheJavaEESpecificationChapter5forfurtherdetails.
CODEEXAMPLE15-5@EJBsAnnotationExample@EJBs({@EJB(Calculator),@EJB(ShoppingCart)})publicclassShoppingCartServlet{//.
.
.
}Chapter15RequirementsrelatedtootherSpecifications193Anexampleofa@Resourceannotationfollows:Intheexamplecodeabove,aservlet,filter,orlistenerdeclaresafieldcatalogDSoftypejavax.
sql.
DataSourceforwhichthereferencetothedatasourceisinjectedbythecontainerpriortothecomponentbeingmadeavailabletotheapplication.
ThedatasourceJNDImappingisinferredfromthefieldname"catalogDS"andtype(javax.
sql.
DataSource).
Moreover,thecatalogDSresourcenolongerneedstobedefinedinthedeploymentdescriptor.
Thesemanticsofthe@ResourceannotationarefurtherdetailedintheCommonAnnotationsfortheJavaPlatformspecification(JSR250)Section2.
3andJavaEESpecificationspecification5.
2.
5.
15.
5.
5@PersistenceContextAnnotationThisannotationspecifiesthecontainermanagedentitymanagerforreferencedpersistenceunits.
Anexample:Thebehaviorthe@PersistenceContextannotationisfurtherdetailedinsection10.
4.
1oftheJavaPersistenceAPI,Version2.
0(JSR317).
15.
5.
6@PersistenceContextsAnnotationThePersistenceContextsannotationallowsmorethanone@PersistenceContexttobedeclaredonaresource.
Thebehaviorthe@PersistenceContextannotationisfurtherdetailedinsection10.
4.
1oftheJavaPersistenceAPI,version2.
0(JSR317).
CODEEXAMPLE15-6@ResourceExample@Resourceprivatejavax.
sql.
DataSourcecatalogDS;publicgetProductsByCategory(){//getaconnectionandexecutethequeryConnectionconn=catalogDS.
getConnection();.
.
}CODEEXAMPLE15-7@PersistenceContextExample@PersistenceContext(type=EXTENDED)EntityManagerem;194JavaServletSpecification15.
5.
7@PersistenceUnitAnnotationThe@PersistenceUnitannotationprovidesEnterpriseJavaBeanscomponentsdeclaredinaservletareferencetoaentitymanagerfactory.
Theentitymanagerfactoryisboundtoaseparatepersistence.
xmlconfigurationfileasdescribedinsection5.
10oftheEJB3.
0specification(JSR220).
Anexample:Thebehaviorthe@PersistenceUnitannotationisfurtherdetailedinsection10.
4.
2oftheJavaPersistenceAPI,version2.
0(JSR317).
15.
5.
8@PersistenceUnitsAnnotationThisannotationallowsformorethanone@PersistentUnitannotationstobedeclaredonaresource.
Thebehaviorthe@PersistenceUnitsannotationisfurtherdetailedinsection10.
4.
2oftheJavaPersistenceAPI,version2.
0(JSR317).
15.
5.
9@PostConstructAnnotationThe@PostConstructannotationisdeclaredonamethodthatdoesnottakeanyarguments,andmustnotthrowanycheckedexceptions.
Thereturnvaluemustbevoid.
ThemethodMUSTbecalledaftertheresourcesinjectionshavebeencompletedandbeforeanylifecyclemethodsonthecomponentarecalled.
Anexample:Theexampleaboveshowsamethodusingthe@PostConstructannotation.
CODEEXAMPLE15-8@PersistenceUnitExample@PersistenceUnitEntityManagerFactoryemf;CODEEXAMPLE15-9@PostConstructExample@PostConstructpublicvoidpostConstruct(){.
.
.
}Chapter15RequirementsrelatedtootherSpecifications195The@PostConstructannotationMUSTbesupportedbyallclassesthatsupportdependencyinjectionandcalledeveniftheclassdoesnotrequestanyresourcestobeinjected.
IfthemethodthrowsanuncheckedexceptiontheclassMUSTnotbeputintoserviceandnomethodonthatinstancecanbecalled.
RefertotheJavaEEspecificationsection2.
5andtheCommonAnnotationsfortheJavaPlatformspecificationsection2.
5formoredetails.
15.
5.
10@PreDestroyAnnotationThe@PreDestroyannotationisdeclaredonamethodofacontainermanagedcomponent.
Themethodiscalledpriortocomponentbeingremovedbythecontainer.
Anexample:Themethodannotatedwith@PreDestroymustreturnvoidandmustnotthrowacheckedexception.
Themethodmaybepublic,protected,packageprivateorprivate.
Themethodmustnotbestatichoweveritmaybefinal.
RefertotheJSR250section2.
6formoredetails.
15.
5.
11@ResourcesAnnotationThe@Resourcesannotationactsasacontainerformultiple@ResourceannotationsbecausetheJavaMetaDataspecificationdoesnotallowformultipleannotationswiththesamenameonthesameannotationtarget.
Anexample:CODEEXAMPLE15-10@PreDestroyExample@PreDestroypublicvoidcleanup(){//cleanupanyopenresources.
.
.
}CODEEXAMPLE15-11@ResourcesExample@Resources({@Resource(name="myDB"type=javax.
sql.
DataSource),@Resource(name="myMQ"type=javax.
jms.
ConnectionFactory)})196JavaServletSpecificationIntheexampleaboveaJMSconnectionfactoryandadatasourcearemadeavailabletotheCalculatorServletbymeansofan@Resourcesannotation.
Thesemanticsofthe@ResourcesannotationarefurtherdetailedintheCommonAnnotationsfortheJavaPlatformspecification(JSR250)section2.
4.
15.
5.
12@RunAsAnnotationThe@RunAsannotationisequivalenttotherun-aselementinthedeploymentdescriptor.
The@RunAsannotationmayonlybedefinedinclassesimplementingthejavax.
servlet.
Servletinterfaceorasubclassthereof.
Anexample:The@RunAs("Admin")statementwouldbeequivalenttodefiningthefollowingintheweb.
xml.
publicclassCalculatorServlet{//.
.
.
}CODEEXAMPLE15-12@RunAsExample@RunAs("Admin")publicclassCalculatorServlet{@EJBprivateShoppingCartmyCart;publicvoiddoGet(HttpServletRequest,req,HttpServletResponseres){//.
.
.
.
myCart.
getTotal();//.
.
.
.
}}//.
.
.
.
}CODEEXAMPLE15-13@RunAsweb.
xmlExampleCalculatorServletAdminCODEEXAMPLE15-11@ResourcesExampleChapter15RequirementsrelatedtootherSpecifications197Theexampleaboveshowshowaservletusesthe@RunAsannotationtopropagatethesecurityidentity"Admin"toanEJBcomponentwhenthemyCart.
getTotal()methodiscalled.
ForfurtherdetailsonpropagatingidentitiesseeSection15.
3.
1,"PropagationofSecurityIdentityinEJBCalls"onpage15-186.
Forfurtherdetailsonthe@RunAsannotationrefertotheCommonAnnotationsfortheJavaPlatformspecification(JSR250)section2.
6.
15.
5.
13@WebServiceRefAnnotationThe@WebServiceRefannotationprovidesareferencetoawebserviceinawebcomponentinsamewayasaresource-refelementwouldinthedeploymentdescriptor.
Anexample:@WebServiceRefprivateMyServiceservice;Inthisexampleareferencetothewebservice"MyService"willbeinjectedtotheclassdeclaringtheannotation.
ThisannotationandbehaviorarefurtherdetailedintheJAX-WSSpecification(JSR224)section7.
15.
5.
14@WebServiceRefsAnnotationThisannotationallowsformorethanone@WebServiceRefannotationstobedeclaredonasingleresource.
ThebehaviorofthisannotationisfurtherdetailedintheJAX-WSSpecification(JSR224)section7.
15.
5.
15ContextsandDependencyInjectionforJavaEErequirementsInaproductthatsupportsContextsandDependencyInjectionforJavaEE(CDI)andinwhichCDIisenabled,implementationsMUSTsupporttheuseofCDImanagedbeans.
Servlets,Filters,ListenersandHttpUpgradeHandlersMUSTsupportCDIinjectionandtheuseofinterceptorsasdescribedinSectionEE.
5.
24,"SupportforDependencyInjection"oftheJavaEE7platformspecification.
198JavaServletSpecification199APPENDIXAChangeLogThisdocumentisthefinalreleaseoftheJavaServlet3.
0ServletspecificationdevelopedundertheJavaCommunityProcessSM(JCP).
A.
1ChangessinceServlet3.
01.
Section1.
6,"CompatibilitywithJavaServletSpecificationVersion2.
5".
Removesubsection1.
6.
1"Listenerordering".
2.
Section2.
3.
3.
3,"Asynchronousprocessing".
AndjavadocofAsyncContext.
a.
ClarifiedthebehaviorofAsyncListener.
onStartAsync.
b.
FixederrorsandcommentsinCodeExamples.
c.
ClarifiedthebehaviorofAsyncContext.
getRequestandAsyncContext.
getResponseaftertheasynchronousrequestiscompletedordispatched.
d.
ClarifiedthebehaviorofAsyncListenerwhenthereisanerror.
3.
AddedSection2.
3.
3.
5,"UpgradeProcessing",andnewclassesProtocolHandlerandWebConnection.
4.
Section3.
2,"Fileupload".
Clarifiedwhenmulti-part/form-dataareprocessed.
5.
AddedAsynchronousIOinSection3.
7,"NonBlockingIO"andSection5.
7,"LifetimeoftheResponseObject".
6.
ClarifiedSection4.
4,"Configurationmethods"thattheServletContextListenermustbedeclaredinthedescriptororannotatedwith@WebListener200JavaServletSpecification7.
AddedHttpSessionIdListenertothelistlistenersinSection4.
4.
3.
1,"voidaddListener(StringclassName)",Section4.
4.
3.
2,"voidaddListener(Tt)",Section4.
4.
3.
3,"voidaddListener(ClasslistenerClass)",Section4.
4.
3.
4,"voidcreateListener(Classclazz)",Section8.
1.
4,"@WebListener"andSection15.
5,"AnnotationsandResourceInjection".
8.
Section4.
4.
3.
5,"AnnotationprocessingrequirementsforprogrammaticallyaddedServlets,FiltersandListeners".
Updatethereference.
9.
Section4.
7,"MultipleHostsandServletContexts".
AddServletContext.
getVirtualServerNamemethod.
10.
Section5.
1,"Buffering".
AndjavadocofServletResponse.
ClarifiedthebehaviorofServletResponse.
reset.
11.
Section6.
2.
1,"FilterLifecycle"(4).
Requiredfiltersandservletprocessinginthesamethread.
12.
Section7.
2,"CreatingaSession".
Addchangesessionid.
13.
Section8.
1,"Annotationsandpluggability",Section8.
2.
1,"Modularityofweb.
xml"andSection1.
6.
1,"Processingannotations".
Clarifythebehaviorofmetadata-complete.
14.
Section8.
1.
1,"@WebServlet".
Programmaticallyaddingservletwithanamedifferentfromthatspecifiedinannotation.
15.
Section8.
2.
2,"Orderingofweb.
xmlandweb-fragment.
xml"andSection8.
2.
4,"Sharedlibraries/runtimespluggability".
TheprocessingofHandlesTypesannotationisappliedirrespectivetosettingofmetadata-complete.
16.
Section8.
2.
3,"Assemblingthedescriptorfromweb.
xml,web-fragment.
xmlandannotations".
Clarifytheorderinwhichlistenersareinvoked.
17.
Section8.
2.
4,"Sharedlibraries/runtimespluggability"ClarifythecreationofinstanceofServletCotnainerInitilizer.
18.
Section9.
4,"TheForwardMethod".
Clarifiedthebehavioroftheresponsewhentherequestisputinasynchronousmode.
19.
TABLE11-2.
Adda"Changestoid"events.
20.
Section10.
9.
2,"ErrorPages"andSection14.
4,"DeploymentDescriptorDiagram".
Adddescriptionfordefaulterrorpage.
21.
Section11.
3.
3,"ListenerRegistration".
Clarifyonordering.
22.
Section12.
2,"SpecificationofMappings".
Clarifythebehaviorofservletsmappedtothesameurl-pattern.
AppendixAChangeLog20123.
Section13.
3,"ProgrammaticSecurity",Section13.
4.
1.
3,"Mapping@HttpConstraintand@HttpMethodConstrainttoXML.
"andSection13.
8.
1,"CombiningConstraints".
Adddescriptionsforrole"*"and"**".
24.
Section13.
6.
3,"FormBasedAuthentication".
Addstatuscode303.
25.
Section13.
6.
3.
1,"LoginFormNotes".
Addautocomplete="off'.
26.
AddSection13.
8.
4,"UncoveredHTTPProtocolMethods".
27.
Section15.
3.
1,"PropagationofSecurityIdentityinEJBCalls".
ExplicitlymentionedtheServlet.
initandServlet.
destroy.
28.
Section15.
5.
15,"ContextsandDependencyInjectionforJavaEErequirements".
AddHttpUpgradeHandlerandaddreferencetoJavaEE7specification.
29.
AddedgenericinServletRequestWrapper,ServletResponseWrapperandHandlesTypes.
30.
JavadocofHttpServletResponse.
sendRedirect:Supportednetwork-pathreference.
31.
AddnewmethodsServletRequest.
getContentLengthLongandServletResponse.
setContentLengthLong.
32.
AddthenewPart.
getSubmittedFileName.
A.
2ChangessinceServlet3.
0ProposedFinalDraft1.
Re-factoredsomeoftheAsyncAPIs-movedaddAsyncListenertoAsyncContextandrenamedittoaddListener.
MovedsetAsyncTimeouttoAsyncContextandrenamedittosetTimeout.
2.
Clarifiedsomeofthesemanticsaroundconcurrentaccesstotherequestandresponseinasyncprocessing.
3.
Updatedpluggabilityrulesforresourcereferenceelements.
4.
Addedanewannotation-@ServletSecurity(andassociatedannotationforthefields)fordefiningsecurityasopposedtore-usingthe@RolesAllowed,@PermitAll,@DenyAll202JavaServletSpecificationA.
3ChangessinceServlet3.
0PublicReview1.
UpdatedisAsyncStartedtoreturnfalseonceadispatchtothecontaineroracalltocompleteisdonefromtheasynchandler2.
Addedorderingsupportforfragments3.
Addedsupportforfileupload4.
AddedsupportforloadingstaticresourcesandJSPsfromJARfilesthatareincludedintheMETA-INF/resourcesdirectoryoftheJARfilewhichisthenbundledintheWEB-INF/libdirectory5.
ChangedannotationnamesbasedonfeedbackonPublicReviewofthespecification6.
Addedprogrammaticlogin/logoutsupport7.
Addedsupportforsecurityrelatedcommonannotations-@RolesAllowed,@PermitAll,@DenyAll8.
ClarifiedwelcomefilesA.
4ChangessinceServlet3.
0EDR1.
Thesuspend/resumeAPIsarenolongerpresentinthespecification.
TheyhavebeenreplacedbystartAsyncandAsyncContextwhichnowhasforwardandcompletemethods.
2.
Annotationnameshavechangedandthereareonlytoplevelannotations.
Themethodlevelannotationsfordeclaringtheservletmethodsarenolongerbeingused.
3.
Therulesforassemblingweb.
xmlfromfragmentsandannotationsisdescribed.
A.
5ChangessinceServlet2.
5MR61.
Addedsupportforannotationsandwebfragments2.
Addedsupportforsuspend/resumetoallowasyncsupportinservlets.
AppendixAChangeLog2033.
AddedsupportforinitializingservletsandfiltersfromtheServletContextatinitializationtime.
4.
AddedsupportforHttpOnlycookiesandallowconfiguringcookies.
5.
AddedconveniencemethodstoServletRequesttogetResponseandServletContextA.
6ChangessinceServlet2.
5MR5A.
6.
1ClarifySRV8.
4"TheForwardMethod"Changethelastsentenceofthesectionwhichcurrentlyis:"BeforetheforwardmethodoftheRequestDispatcherinterfacereturns,theresponsecontentmustbesentandcommitted,andclosedbytheservletcontainer.
"toread:"BeforetheforwardmethodoftheRequestDispatcherinterfacereturnswithoutexception,theresponsecontentmustbesentandcommitted,andclosedbytheservletcontainer.
IfanerroroccursinthetargetoftheRequestDispatcher.
forward()theexceptionmaybepropogatedbackthroughallthecallingfiltersandservletsandeventuallybacktothecontainer.
"A.
6.
2UpdateDeploymentdescriptor"http-methodvaluesallowed"Thefacetforhttp-methodelementinthedeploymentdescriptoriscurrentlymorerestrictivethanthehttpspecification.
Thefollowingchangeisbeingmadetothedescriptortoallowthesetofmethodnamesasdefinedbythehttpspecification.
Thepatternvalueofhttp-methodTypeisbeingchangedfromtocloselymatchwhattheHTTPspecificationlistsasallowableHTTPmethodsnames.
204JavaServletSpecificationA.
6.
3ClarifySRV7.
7.
1"ThreadingIssues"Changetheparagraphwhichcurrentlyis:"Multipleservletsexecutingrequestthreadsmayhaveactiveaccesstoasinglesessionobjectatthesametime.
TheDeveloperhastheresponsibilityforsynchronizingaccesstosessionresourcesasappropriate.
"toread:"Multipleservletsexecutingrequestthreadsmayhaveactiveaccesstothesamesessionobjectatthesametime.
Thecontainermustensurethatmanipulationofinternaldatastructuresrepresentingthesessionattributesisperformedinathreadsafemanner.
TheDeveloperhastheresponsibilityforthreadsafeaccesstotheattributeobjectsthemselves.
ThiswillprotecttheattributecollectioninsidetheHttpSessionobjectfromconcurrentaccess,eliminatingtheopportunityforanapplicationtocausethatcollectiontobecomecorrupted.
"A.
7ChangesSinceServlet2.
5MR2A.
7.
1UpdatedAnnotationRequirementsforJavaEEcontainersAddedEJBs,PreDestroy,PeristenceContext,PersistenceContexts,PersistenceUnit,andPersistenceUnitswithdescriptionstothelistofrequiredJavaEEcdontainerannotationsinSection15.
5,"AnnotationsandResourceInjection".
A.
7.
2UpdatedJavaEnterpriseEditionRequirementsUpdatedtheAnnotationstothefinalJavaEEannotationnames.
Alsoupdatedthe"full"attributeintheweb.
xmltobe"metadata-complete".
A.
7.
3ClarifiedHttpServletRequest.
getRequestURL()TheAPIdocumentationforjavax.
servlet.
http.
HttpServletRequest.
getRequestURL()wasclarified.
Thetextinitalicswasadded:AppendixAChangeLog205IfthisrequesthasbeenforwardedusingRequestDispatcher.
forward(ServletRequest,ServletResponse),theserverpathinthereconstructedURLmustreflectthepathusedtoobtaintheRequestDispatcher,andnottheserverpathspecifiedbytheclient.
BecausethismethodreturnsaStringBuffer,notastring,youcanmodifytheURLeasily,forexample,toappendqueryparameters.
A.
7.
4RemovalofIllegalStateExceptionfromHttpSession.
getId()TheHttpSessionBindingListenercallsthevalueUnboundeventafterthesessionhasbeenexpired,unfortunately,theHttpSession.
getId()methodisoftenusedinthisscenarioandissupposedtothrowanIllegalStateException.
TheservletEGagreedtoremovetheexceptionfromtheAPItopreventthesetypesofexceptions.
A.
7.
5ServletContext.
getContextPath()ThemethodgetContextPath()wasaddedtotheServletContextintheAPI.
Thedescriptionisasfollows:publicjava.
lang.
StringgetContextPath()Returnsthecontextpathofthewebapplication.
ThecontextpathistheportionoftherequestURIthatisusedtoselectthecontextoftherequest.
ThecontextpathalwayscomesfirstinarequestURI.
Thepathstartswitha"/"characterbutdoesnotendwitha"/"character.
Forservletsinthedefault(root)context,thismethodreturns"".
Itispossiblethataservletcontainermaymatchacontextbymorethanonecontextpath.
InsuchcasesgetContextPath()willreturntheactualcontextpathusedbytherequestanditmaydifferfromthepathreturnedbythismethod.
Thecontextpathreturnedbythismethodshouldbeconsideredastheprimeorpreferredcontextpathoftheapplication.
Returns:Thecontextpathofthewebapplication.
HttpServletRequest.
getContextPath()wasupdatedtoclarifyitsrelationshipwiththeServletContext.
getContextPath()method.
Theclarificationisasfollows.
Itispossiblethataservletcontainermaymatchacontextbymorethanonecontextpath.
Insuchcasesthismethodwillreturntheactualcontextpathusedbytherequestanditmaydifferfromthepathreturnedbythe206JavaServletSpecificationServletContext.
getContextPath()method.
ThecontextpathreturnedbyServletContext.
getContextPath()shouldbeconsideredastheprimeorpreferredcontextpathoftheapplication.
A.
7.
6Requirementforweb.
xmlinwebapplicationsSection10.
13,"Inclusionofaweb.
xmlDeploymentDescriptor"wasaddedwhichremovesrequirementforJavaEEcompliantwebapplications.
Thesectionisasfollows:AwebapplicationisNOTrequiredtocontainaweb.
xmlifitdoesNOTcontainanyServlet,Filter,orListenercomponents.
InotherwordsanapplicationcontainingonlystaticfilesorJSPpagesdoesnotrequireaweb.
xmltobepresent.
A.
8ChangesSinceServlet2.
4A.
8.
1SessionClarificationClarifiedSection7.
3,"SessionScope"toallowforbettersupportofsessionidsbeingusedinmorethanonecontext.
ThiswasdonetosupportthePortletspecification(JSR168).
AddedthefollowingparagraphattheendofSection7.
3:"Additionally,sessionsofacontextmustberesumablebyrequestsintothatcontextregardlessofwhethertheirassociatedcontextwasbeingaccesseddirectlyorasthetargetofarequestdispatchatthetimethesessionswerecreated.
"MadethechangesinSection9.
3,"TheIncludeMethod"byreplacingthefollowingtext:"Itcannotsetheadersorcallanymethodthataffectstheheadersoftheresponse.
Anyattempttodosomustbeignored.
"withthefollowing:"Itcannotsetheadersorcallanymethodthataffectstheheadersoftheresponse,withtheexceptionoftheHttpServletRequest.
getSession()andHttpServletRequest.
getSession(boolean)methods.
Anyattempttosettheheadersmustbeignored,andanycalltoHttpServletRequest.
getSession()orHttpServletRequest.
getSession(boolean)thatwouldrequireaddingaCookieresponseheadermustthrowanIllegalStateExceptioniftheresponsehasbeencommitted.
"AppendixAChangeLog207A.
8.
2FilterAllDispatchesModifiedSection6.
2.
5,"FiltersandtheRequestDispatcher"toclarifyawaytomapafiltertoallservletdispatchesbyappendingthefollowingtexttotheendofthesection:Finally,thefollowingcodeusesthespecialservletname'*':ThiscodewouldresultintheAllDispatchFilterbeinginvokedonrequestdispatcherforward()callsforallrequestdispatchersobtainedbynameorbypath.
A.
8.
3MultipleOccurrencesofServletMappingsPreviousversionsoftheservletschemaallowsonlyasingleurl-patternorservletnameperservletmapping.
ForservletsmappedtomultipleURLsthisresultsinneedlessrepetitionofwholemappingclauses.
Thedeploymentdescriptorservlet-mappingTypewasupdatedto:CODEEXAMPLEA-1Exampleofspecialservletname'*'AllDispatchFilter*FORWARDCODEEXAMPLEA-2servlet-mappingTypedescriptor208JavaServletSpecificationA.
8.
4MultipleOccurrencesFilterMappingsPreviousversionsoftheservletschemaallowsonlyasingleurl-patterninafiltermapping.
ForfiltersmappedtomultipleURLsthisresultsinneedlessrepetitionofwholemappingclauses.
Thedeploymentdescriptorschemathefilter-mappingTypewasupdatedto:Thischangeallowsmultiplepatternsandservletnamestobedefinedinasinglemappingascanbeseeninthefollowingexample:Section6.
2.
4,"ConfigurationofFiltersinaWebApplication"wasupdatedtoclarifythecaseswheretherearemultiplemappingswiththefollowingtext:"Ifafiltermappingcontainsbothand,thecontainermustexpandthefiltermappingintomultiplefiltermappings(oneforeachand),preservingtheorderoftheandelements.
"CODEEXAMPLEA-3Updatedfilter-mappingTypeschemaCODEEXAMPLEA-4FiltermappingexampleDemoFilter/foo/*/bar/*LoggerREQUESTERRORAppendixAChangeLog209Anexampleswasalsoprovidedtoclarifycaseswhentherearemultiplemappings.
A.
8.
5SupportAlternativeHTTPMethodswithAuthorizationConstraintsThepreviousServlet2.
4schemarestrictedHTTPmethodstoGET,POST,PUT,DELETE,HEAD,OPTIONS,andTRACE.
Theschemahttp-methodTypewaschangedfrom:Tothefollowing:Thehttp-methodelementsnowneedtobeatokenasdescribedinHTTP1.
1specificationsection2.
2.
CODEEXAMPLEA-5Servlet2.
4http-methodTypeschema.
.
.
CODEEXAMPLEA-6Servlet2.
5http-methodTypeschemaAHTTPmethodtypeasdefinedinHTTP1.
1section2.
2.
210JavaServletSpecificationA.
8.
6MinimumJ2SERequirementServlet2.
5ContainersnowrequireJ2SE5.
0astheminimumJavaversion.
Section1.
2,"WhatisaServletContainer"wasupdatedtoreflectthisrequirement.
A.
8.
7AnnotationsandResourceInjectionJavaEEtechnologycompliantcontainersrequireannotationsandresourceinjectiononservlets,filters,andlisteners.
Section15.
5,"AnnotationsandResourceInjection"describestheannotationsandresourceinjectioninfurtherdetail.
A.
8.
8SRV.
9.
9("ErrorHandling")RequirementRemovedSection10.
9.
1,"RequestAttributes"definesthefollowingrequirement:IfthelocationoftheerrorhandlerisaservletoraJSPpage:[.
.
.
]TheresponsesetStatusmethodisdisabledandignoredifcalled.
[.
.
.
]TheJSP2.
1EGhasaskedthatthisrequirementaboveberemovedtoallowJSPerrorpagestoupdatetheresponsestatus.
A.
8.
9HttpServletRequest.
isRequestedSessionIdValid()ClarificationTheAPIclarificationbetterdescribeswhathappenswhenaclientdidnotspecifyasessionid.
TheAPIdocumentationwasupdatedtospecifywhenfalseisreturned.
TheAPIdocumentationnowstates:ReturnsfalseiftheclientdidnotspecifyanysessionID.
A.
8.
10SRV.
5.
5("ClosureofResponseObject")ClarificationThebehaviorinSection5.
6,"ClosureofResponseObject"theresponse'scontentlengthissetto0viaresponse.
setHeader("Content-Length","0")andanysubsequentlysetHeader()callsareignored.
AppendixAChangeLog211Section5.
6,"ClosureofResponseObject"wasupdatedtoallowallheaderstobesetbychanging:"TheamountofcontentspecifiedinthesetContentLengthmethodoftheresponseandhasbeenwrittentotheresponse"Tothefollowing:"TheamountofcontentspecifiedinthesetContentLengthmethodoftheresponsehasbeengreaterthanzeroandhasbeenwrittentotheresponse"A.
8.
11ServletRequest.
setCharacterEncoding()ClarifiedTheAPIwasupdatedtodescribedthebehaviorifthemethodiscalledafterthegetReader()wascalled.
IfthegetReader()iscalledtherewillbenoeffect.
A.
8.
12JavaEnterpriseEditionRequirementsChapter15,"RequirementsrelatedtootherSpecificationsdetailsallrequirementsofaJavaEEcontainer.
Previouslytherequirementsweremixedintoeachchapter.
A.
8.
13Servlet2.
4MRChangeLogUpdatesAddedAddedthechangesfromtheServlet2.
4MaintenanceReview.
Thesechangesincludegrammarandtypographicalfixes.
A.
8.
14SynchronizedAccessSessionObjectClarifiedSection7.
7.
1,"ThreadingIssues"wasupdatedtoclarifythataccesstothesessionobjectshouldbesynchronized.
A.
9ChangesSinceServlet2.
3Optional"X-Powered-By"headerisaddedintheresponse(5.
2)Clarificationof"overlappingconstraint"(12.
8.
1,12.
8.
2)Addthesectiontoclarifytheprocessorderatthetimeofwebapplicationdeployment(9.
12)212JavaServletSpecificationClarificationthatthesecuritymodelisalsoappliedtofilter(12.
2)Changethestatuscodefrom401to200whenFORMauthenticationisfailedasthereisnoappropriateerrorstatuscodeinHTTP/1.
1(12.
5.
3)Clarificationofthewrapperobjects(6.
2.
2)Clarificationofoverridingtheplatformclasses(9.
7.
2)Clarificationofwelcomefile(9.
10)Clarificationofinternationalization-therelationshipamongsetLocale,setContentType,andsetCharacterEncoding(5.
4,14.
2.
22)ClarificationofServletRequestListenerandServletRequestAttributeListenerdescription(14.
2.
18,14.
2.
20)AddHttpSessionActivationListenerandHttpSessionBindingListenerintotheTable10-1.
Changetheword"authconstraint"to"authorizationconstraint"(12.
8)Add"Since"taginthenewlyaddedmethodsinjavadoc(14.
2.
16,14.
2.
22)FixthedatatypeoftoxsdIntegerTypeinschema(13.
3)Clarificationwhenthelistenerthrowstheunhandledexception(10.
6)Clarificationofthe"sharedlibrary"(9.
7.
1)Clarificationofthecontainer'smechanismfortheextension(9.
7.
1,thirdparagraph)HttpSession.
logoutmethodwasremoved.
Theportableauthenticationmechanismwillbeaddressedinthenextversionofthisspecificationandlogoutwillalsobediscussedinthatscope.
(12.
10)Itisnowarecommendation,insteadofarequirement,thatthereferencetotherequestandresponseobjectshouldnotbegiventotheobjectinotherthreads-basedontherequirementfromJSR-168.
Warningsareaddedwhenthethreadcreatedbytheapplicationusestheobjectsmanagedbythecontainer.
(2.
3.
3.
3)Itisnowarecommendation,thatthedispatchshouldoccurinthesamethreadofthesameJVMastheoriginalrequest-basedontherequirementfromJSR-168(8.
2)Clarificationof"wrap"(6.
2.
2)Clarificationofhandlingthepathparameterforthemapping(11.
1)Addthedescriptionaboutthe"HTTPchunk"inHttpServlet.
doGetmethod(15.
1.
2)J2SE1.
3istheminimumversionoftheunderlyingJavaplatformwithwhichservletcontainersmustbebuilt(1.
2)ClarificationofServletResponse.
setBufferSizemethod(5.
1)ClarificationofServletRequest.
getServerNameandgetServerPort(14.
2.
16.
1)ClarificationofInternationalization(5.
4,14.
2.
22)Clarificationoftheredirectionofthewelcomefile(9.
10)ClarificationofServletContextListener.
contextInitialized(14.
2.
12.
1)ClarificationofHttpServletRequest.
getRequestedSessionId-makingitclearthatitreturnsthesessionIDspecifiedbytheclient(15.
1.
3.
2)Clarificationoftheclassloaderfortheextensions-theclassloadermustbethesameforallwebapplicationswithinthesameJVM(9.
7.
1)ClarificationofthecasewhenServletRequestListenerthrowsanunhandledexception(10.
6,14.
2.
20)ClarificationofthescopeofServletRequestListener(14.
2.
20)AppendixAChangeLog213Addthedescriptionaboutthecasewhenthecontainerhasacachingmechanism(1.
2)ValidatingdeploymentdescriptoragainsttheschemaisrequiredforJavaEEcontainers(13.
2)Subelementsundercanbeinanarbitraryorder(13.
2)Oneexampleofthecontainer'srejectingthewebapplicationwasremovedduetothecontradictionwithSRV.
11.
1(9.
5)url-patternTypeischangedfromj2ee:stringtoxsd:string(13)Thesub-elementsunderindeploymentdescriptorcanbeinthearbitraryorder(13)Thecontainermustinformadeveloperwithadescriptiveerrormessagewhendeploymentdescriptorfilecontainsanillegalcharacterormultipleelementsof,,or(13)Extensibilityofdeploymentdescriptorwasremoved(13)SectionSRV.
1.
6added-describingthecompatibilityissuewiththepreviousversionofthisspecification(1.
6)NewattributesareaddedinRequestDispatcher.
forwardmethod(8.
4.
2)NewmethodsinServletRequestinterfaceandServletRequestWrapper(14.
2.
16.
1)TheinterfaceSingleThreadModelwasdeprecated((2.
2.
1,2.
3.
3.
1,14.
2.
24)ChangethenameofthemethodServletRequestEvent.
getRequesttoServletRequestEvent.
getServletRequest(14.
2.
19.
2)Clarificationofthe"request"toaccesstoWEB-INFdirectory(9.
5)ClarificationofthebehaviorofServletRequest.
setAttribute-change"value"to"object"in"Ifthevaluepassedinisnull,"(14.
2.
16.
1)FixtheinconsistencybetweenthisspecificationandHttpServletRequest,getServletPath-thereturnvaluestartswith"/"(15.
1.
3.
2)FixtheinconsistencybetweenthisspecificationandHttpServletRequest.
getPathInfo-thereturnvaluestartswith"/"(15.
1.
3.
2)FixtheinconsistencybetweenthisspecificationandHttpServletRequest.
getPathTranslated-addthecasewhenthecontainercannottranslatethepath(15.
1.
3.
2)AllowHttpServletRequest.
getAuthTypetoreturnnotonlypre-definedfourauthenticationschemebutalsothecontainer-specificscheme(15.
1.
3.
2)ChangethebehaviorofttpSessionListener.
sessionDestroyedtonotifybeforethesessionisinvalidated(15.
1.
14.
1)Fixthewrongstatuscodeof403to404(9.
5,9.
6)Element"taglib"shouldbe"jsp-config"(13.
2)FixtheversionnumberofJSPspecificationto2.
0Fixthewrongformats(5.
5,6.
2.
5,12.
8.
3,12.
9)HTTP/1.
1isnowrequired(1.
2)inismandatory(13.
4)ClarificationofIllegalArgumentExceptioninthedistributedenvironments(7.
7.
2)Clarificationoferrorpagehandling(9.
9.
1,9.
9.
2,9.
9.
3,6.
2.
5)ClarificationofSecurityConstraints,especiallyinthecaseofoverlappingconstraints(12.
8)Clarificationofthecasewhenelementisnotspecified(13.
4)Clarificationofthecasewhentheresourceispermanentlyunavailable(2.
3.
3.
2)214JavaServletSpecificationAddmissinggetParameterMap()intheenumeratedlist(4.
1)Clarificationofthestatuscodewhen/WEB-INF/resourceisaccessed(9.
5)Clarificationofthestatuscodewhen/META-INF/resourceisaccessed(9.
6)Changexsd:stringtoj2ee:stringindeploymentdescriptor(13.
4)Extensibilityofdeploymentdescriptors(SRV.
13)XMLSchemadefinitionofdeploymentdescriptor(SRV.
13)Requestlisteners(SRV.
10andAPIchange)NewAPI:ServletRequestListener,ServletRequestAttributeListenerandassociatedeventclassesAbilitytouseFiltersundertheRequestDispatcher(6.
2.
5)Requiredclassloaderextensionmechanism(9.
7.
1)Listenerexceptionhandling(10.
6)Listenerordervs.
servletinit()/destroy()clarification(ServletContextListenerjavadocchange)ServletsmappedtoWEB-INF/responsehandling(9.
5)Requestdispatcher/pathmatchingrules(8.
1)Welcomefilescanbeservlets(9.
10)Internationalizationenhancements(5.
4,14,2,22,15.
1.
5)SC_FOUND(302)addition(15.
1.
5)"Relativepath"ingetRequestDispatcher()mustberelativeagainstthecurrentservlet(8.
1)BugfixintheexampleofXML(13.
7.
2)ClarificationofaccessbygetResource"onlytotheresource"(3.
5)ClarificationofSERVER_NAMEandSERVER_PORTingetServerName()andgetServerPort()(14.
2.
16)Clarification:"run-as"identitymustapplytoallcallsfromaservletincludinginit()anddestroy()(12.
7)Login/logoutdescriptionandmethodsadded(12.
10,15.
1.
7)Glossary-215GlossaryAApplicationDeveloperTheproducerofawebapplication.
TheoutputofanApplicationDeveloperisasetofservletclasses,JSPpages,HTMLpages,andsupportinglibrariesandfiles(suchasimages,compressedarchivefiles,etc.
)forthewebapplication.
TheApplicationDeveloperistypicallyanapplicationdomainexpert.
Thedeveloperisrequiredtobeawareoftheservletenvironmentanditsconsequenceswhenprogramming,includingconcurrencyconsiderations,andcreatethewebapplicationaccordingly.
ApplicationAssemblerTakestheoutputoftheApplicationDeveloperandensuresthatitisadeployableunit.
Thus,theinputoftheApplicationAssembleristheservletclasses,JSPpages,HTMLpages,andothersupportinglibrariesandfilesforthewebapplication.
TheoutputoftheApplicationAssemblerisawebapplicationarchiveorawebapplicationinanopendirectorystructure.
DDeployerTheDeployertakesoneormorewebapplicationarchivefilesorotherdirectorystructuresprovidedbyanApplicationDeveloperanddeploystheapplicationintoaspecificoperationalenvironment.
TheoperationalenvironmentincludesGlossary-216JavaServletSpecificationaspecificservletcontainerandwebserver.
TheDeployermustresolvealltheexternaldependenciesdeclaredbythedeveloper.
Toperformhisrole,thedeployerusestoolsprovidedbytheServletContainerProvider.
TheDeployerisanexpertinaspecificoperationalenvironment.
Forexample,theDeployerisresponsibleformappingthesecurityrolesdefinedbytheApplicationDevelopertotheusergroupsandaccountsthatexistintheoperationalenvironmentwherethewebapplicationisdeployed.
PprincipalAprincipalisanentitythatcanbeauthenticatedbyanauthenticationprotocol.
Aprincipalisidentifiedbyaprincipalnameandauthenticatedbyusingauthenticationdata.
Thecontentandformatoftheprincipalnameandtheauthenticationdatadependontheauthenticationprotocol.
Rrole(development)Theactionsandresponsibilitiestakenbyvariouspartiesduringthedevelopment,deployment,andrunningofawebapplication.
Insomescenarios,asinglepartymayperformseveralroles;inothers,eachrolemaybeperformedbyadifferentparty.
role(security)AnabstractnotionusedbyanApplicationDeveloperinanapplicationthatcanbemappedbytheDeployertoauser,orgroupofusers,inasecuritypolicydomain.
SsecuritypolicydomainThescopeoverwhichsecuritypoliciesaredefinedandenforcedbyasecurityadministratorofthesecurityservice.
Asecuritypolicydomainisalsosometimesreferredtoasarealm.
securitytechnologydomainThescopeoverwhichthesamesecuritymechanism,suchasKerberos,isusedtoenforceasecuritypolicy.
Multiplesecuritypolicydomainscanexistwithinasingletechnologydomain.
Glossary-217ServletContainerProviderAvendorthatprovidestheruntimeenvironment,namelytheservletcontainerandpossiblythewebserver,inwhichawebapplicationrunsaswellasthetoolsnecessarytodeploywebapplications.
TheexpertiseoftheContainerProviderisinHTTP-levelprogramming.
Sincethisspecificationdoesnotspecifytheinterfacebetweenthewebserverandtheservletcontainer,itislefttotheContainerProvidertosplittheimplementationoftherequiredfunctionalitybetweenthecontainerandtheserver.
servletdefinitionAuniquenameassociatedwithafullyqualifiedclassnameofaclassimplementingtheServletinterface.
Asetofinitializationparameterscanbeassociatedwithaservletdefinition.
servletmappingAservletdefinitionthatisassociatedbyaservletcontainerwithaURLpathpattern.
Allrequeststothatpathpatternarehandledbytheservletassociatedwiththeservletdefinition.
SystemAdministratorThepersonresponsiblefortheconfigurationandadministrationoftheservletcontainerandwebserver.
Theadministratorisalsoresponsibleforoverseeingthewell-beingofthedeployedwebapplicationsatruntime.
Thisspecificationdoesnotdefinethecontractsforsystemmanagementandadministration.
TheadministratortypicallyusesruntimemonitoringandmanagementtoolsprovidedbytheContainerProviderandservervendorstoaccomplishthesetasks.
Glossary-218JavaServletSpecificationUuniformresourcelocator(URL)Acompactstringrepresentationofresourcesavailableviathenetwork.
OncetheresourcerepresentedbyaURLhasbeenaccessed,variousoperationsmaybeperformedonthatresource.
1AURLisatypeofuniformresourceidentifier(URI).
URLsaretypicallyoftheform:///Forthepurposesofthisspecification,weareprimarilyinterestedinHTT-basedURLswhichareoftheform:http[s]://[:port]/[]Forexample:http://java.
sun.
com/products/servlet/index.
htmlhttps://javashop.
sun.
com/purchaseInHTTP-basedURLs,the'/'characterisreservedtoseparateahierarchicalpathstructureintheURL-pathportionoftheURL.
Theserverisresponsiblefordeterminingthemeaningofthehierarchicalstructure.
ThereisnocorrespondencebetweenaURL-pathandagivenfilesystempath.
WwebapplicationAcollectionofservlets,JSPpages,HTMLdocuments,andotherwebresourceswhichmightincludeimagefiles,compressedarchives,andotherdata.
Awebapplicationmaybepackagedintoanarchiveorexistinanopendirectorystructure.
Allcompatibleservletcontainersmustacceptawebapplicationandperformadeploymentofitscontentsintotheirruntime.
Thismaymeanthatacontainercanruntheapplicationdirectlyfromawebapplicationarchivefileoritmaymeanthatitwillmovethecontentsofawebapplicationintotheappropriatelocationsforthatparticularcontainer.
1.
SeeRFC1738Glossary-219webapplicationarchiveAsinglefilethatcontainsallofthecomponentsofawebapplication.
ThisarchivefileiscreatedbyusingstandardJARtoolswhichallowanyorallofthewebcomponentstobesigned.
Webapplicationarchivefilesareidentifiedbythe.
warextension.
Anewextensionisusedinsteadof.
jarbecausethatextensionisreservedforfileswhichcontainasetofclassfilesandthatcanbeplacedintheclasspathordoubleclickedusingaGUItolaunchanapplication.
Asthecontentsofawebapplicationarchivearenotsuitableforsuchuse,anewextensionwasinorder.
webapplication,distributableAwebapplicationthatiswrittensothatitcanbedeployedinawebcontainerdistributedacrossmultipleJavavirtualmachinesrunningonthesamehostordifferenthosts.
Thedeploymentdescriptorforsuchanapplicationusesthedistributableelement.
Glossary-220JavaServletSpecification

racknerd:美国大硬盘服务器(双路e5-2640v2/64g内存/256gSSD+160T SAS)$389/月

racknerd在促销美国洛杉矶multacom数据中心的一款大硬盘服务器,用来做存储、数据备份等是非常划算的,而且线路还是针对亚洲有特别优化处理的。双路e5+64G内存,配一个256G的SSD做系统盘,160T SAS做数据盘,200T流量每个月,1Gbps带宽,5个IPv4,这一切才389美元...洛杉矶大硬盘服务器CPU:2 * e5-2640v2内存:64G(可扩展至128G,+$64)硬...

快快云:香港沙田CN2/美国Cera大宽带/日本CN2,三网直连CN2 GIA云服务器和独立服务器

快快云怎么样?快快云是一家成立于2021年的主机服务商,致力于为用户提供高性价比稳定快速的主机托管服务,快快云目前提供有香港云服务器、美国云服务器、日本云服务器、香港独立服务器、美国独立服务器,日本独立服务器。快快云专注为个人开发者用户,中小型,大型企业用户提供一站式核心网络云端服务部署,促使用户云端部署化简为零,轻松快捷运用云计算!多年云计算领域服务经验,遍布亚太地区的海量节点为业务推进提供强大...

腾讯云轻量应用服务器关于多个实例套餐带宽

腾讯云轻量应用服务器又要免费升级配置了,之前已经免费升级过一次了(腾讯云轻量应用服务器套餐配置升级 轻量老用户专享免费升配!),这次在上次的基础上再次升级。也许这就是良心云吧,名不虚传。腾讯云怎么样?腾讯云好不好。腾讯云轻量应用服务器 Lighthouse 是一种易于使用和管理、适合承载轻量级业务负载的云服务器,能帮助个人和企业在云端快速构建网站、博客、电商、论坛等各类应用以及开发测试环境,并提供...

500InternalServerError为你推荐
abolishingios11朝阳分局犯罪嫌疑人标准化信息采集系统绑定ipadwindows键是哪个Win键是什么?win7telnet怎样在win7下打开telnet 命令联通iphone4北京 朝阳区 哪家联通店可以卖Iphone4的,本周周末过去买icloudiphone没开启icloud的iphone怎么用find my iphone找回迅雷雷鸟雷鸟手机谁用过性能怎样样?win7还原系统win7如何一键还原?杀毒软件免费下载2013排行榜哪里有免费好用的杀毒软件
中文域名查询 天津服务器租赁 中国万网虚拟主机 80vps 国外idc 紫田 卡巴斯基官方免费版 国外代理服务器软件 phpmyadmin配置 免费申请个人网站 cdn加速是什么 idc查询 dnspod 防cc攻击 申请免费空间 免费个人主页 cdn网站加速 114dns 黑科云 闪讯网 更多