finishedpathinfo

pathinfo  时间:2021-05-19  阅读:()
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)RobertGoff(IBM)RichardHightowerSethHodgson(AdobeSystemsInc.
)RemyMaucherat(RedHat)MinoruNitta(FujitsuLimited)ChangPaek(TmaxSoft,Inc)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.
TheResponse435.
1Buffering435.
2Headers445.
3NonBlockingIO455.
4ConvenienceMethods465.
5Internationalization475.
6ClosureofResponseObject485.
7LifetimeoftheResponseObject486.
Filtering496.
1Whatisafilter496.
1.
1ExamplesofFilteringComponents506.
2MainConcepts506.
2.
1FilterLifecycle506.
2.
2WrappingRequestsandResponses526.
2.
3FilterEnvironment526.
2.
4ConfigurationofFiltersinaWebApplication536.
2.
5FiltersandtheRequestDispatcher567.
Sessions597.
1SessionTrackingMechanisms597.
1.
1Cookies597.
1.
2SSLSessions60Contentsxiii7.
1.
3URLRewriting607.
1.
4SessionIntegrity607.
2CreatingaSession607.
3SessionScope617.
4BindingAttributesintoaSession627.
5SessionTimeouts627.
6LastAccessedTimes637.
7ImportantSessionSemantics637.
7.
1ThreadingIssues637.
7.
2DistributedEnvironments637.
7.
3ClientSemantics648.
Annotationsandpluggability658.
1Annotationsandpluggability658.
1.
1@WebServlet658.
1.
2@WebFilter678.
1.
3@WebInitParam678.
1.
4@WebListener678.
1.
5@MultipartConfig688.
1.
6Otherannotations/conventions688.
2Pluggability698.
2.
1Modularityofweb.
xml698.
2.
2Orderingofweb.
xmlandweb-fragment.
xml718.
2.
3Assemblingthedescriptorfromweb.
xml,web-fragment.
xmlandannotations768.
2.
4Sharedlibraries/runtimespluggability898.
3JSPcontainerpluggability918.
4Processingannotationsandfragments929.
DispatchingRequests93xivJavaServletSpecification9.
1ObtainingaRequestDispatcher939.
1.
1QueryStringsinRequestDispatcherPaths949.
2UsingaRequestDispatcher949.
3TheIncludeMethod959.
3.
1IncludedRequestParameters959.
4TheForwardMethod969.
4.
1QueryString969.
4.
2ForwardedRequestParameters969.
5ErrorHandling979.
6ObtaininganAsyncContext979.
7TheDispatchMethod989.
7.
1QueryString989.
7.
2DispatchedRequestParameters9810.
WebApplications10110.
1WebApplicationsWithinWebServers10110.
2RelationshiptoServletContext10110.
3ElementsofaWebApplication10210.
4DeploymentHierarchies10210.
5DirectoryStructure10210.
5.
1ExampleofApplicationDirectoryStructure10410.
6WebApplicationArchiveFile10410.
7WebApplicationDeploymentDescriptor10410.
7.
1DependenciesOnExtensions10510.
7.
2WebApplicationClassLoader10510.
8ReplacingaWebApplication10610.
9ErrorHandling10610.
9.
1RequestAttributes10610.
9.
2ErrorPages107Contentsxv10.
9.
3ErrorFilters10910.
10WelcomeFiles10910.
11WebApplicationEnvironment11010.
12WebApplicationDeployment11110.
13Inclusionofaweb.
xmlDeploymentDescriptor11111.
ApplicationLifecycleEvents11311.
1Introduction11311.
2EventListeners11311.
2.
1EventTypesandListenerInterfaces11411.
2.
2AnExampleofListenerUse11511.
3ListenerClassConfiguration11511.
3.
1ProvisionofListenerClasses11511.
3.
2DeploymentDeclarations11611.
3.
3ListenerRegistration11611.
3.
4NotificationsAtShutdown11611.
4DeploymentDescriptorExample11611.
5ListenerInstancesandThreading11711.
6ListenerExceptions11711.
7DistributedContainers11811.
8SessionEvents11812.
MappingRequeststoServlets11912.
1UseofURLPaths11912.
2SpecificationofMappings12012.
2.
1ImplicitMappings12012.
2.
2ExampleMappingSet12113.
Security12313.
1Introduction123xviJavaServletSpecification13.
2DeclarativeSecurity12413.
3ProgrammaticSecurity12413.
4ProgrammaticAccessControlAnnotations12613.
4.
1@ServletSecurityAnnotation12613.
4.
1.
1Examples12913.
4.
1.
2Mapping@ServletSecuritytosecurity-constraint13013.
4.
1.
3Mapping@HttpConstraintand@HttpMethodConstrainttoXML.
13213.
4.
2setServletSecurityofServletRegistration.
Dynamic13413.
5Roles13413.
6Authentication13513.
6.
1HTTPBasicAuthentication13513.
6.
2HTTPDigestAuthentication13613.
6.
3FormBasedAuthentication13613.
6.
3.
1LoginFormNotes13713.
6.
4HTTPSClientAuthentication13813.
6.
5AdditionalContainerAuthenticationMechanisms13813.
7ServerTrackingofAuthenticationInformation13813.
8SpecifyingSecurityConstraints13913.
8.
1CombiningConstraints14013.
8.
2Example14113.
8.
3ProcessingRequests14313.
9DefaultPolicies14413.
10LoginandLogout14414.
DeploymentDescriptor14714.
1DeploymentDescriptorElements14714.
2RulesforProcessingtheDeploymentDescriptor14814.
3DeploymentDescriptor149Contentsxvii14.
4DeploymentDescriptorDiagram14914.
5Examples17214.
5.
1ABasicExample17314.
5.
2AnExampleofSecurity17415.
RequirementsrelatedtootherSpecifications17715.
1Sessions17715.
2WebApplications17715.
2.
1WebApplicationClassLoader17715.
2.
2WebApplicationEnvironment17815.
2.
3JNDINameforWebModuleContextRootURL17815.
3Security17915.
3.
1PropagationofSecurityIdentityinEJBCalls18015.
3.
2ContainerAuthorizationRequirements18015.
3.
3ContainerAuthenticationRequirements18015.
4Deployment18115.
4.
1DeploymentDescriptorElements18115.
4.
2PackagingandDeploymentofJAX-WSComponents18115.
4.
3RulesforProcessingtheDeploymentDescriptor18315.
5AnnotationsandResourceInjection18315.
5.
1@DeclareRoles18415.
5.
2@EJBAnnotation18515.
5.
3@EJBsAnnotation18615.
5.
4@ResourceAnnotation18615.
5.
5@PersistenceContextAnnotation18715.
5.
6@PersistenceContextsAnnotation18715.
5.
7@PersistenceUnitAnnotation18815.
5.
8@PersistenceUnitsAnnotation18815.
5.
9@PostConstructAnnotation188xviiiJavaServletSpecification15.
5.
10@PreDestroyAnnotation18915.
5.
11@ResourcesAnnotation18915.
5.
12@RunAsAnnotation19015.
5.
13@WebServiceRefAnnotation19115.
5.
14@WebServiceRefsAnnotation19115.
5.
15ManagedBeansandJSR299requirements191A.
ChangeLog193A.
1ChangessinceServlet3.
0193A.
2ChangessinceServlet3.
0ProposedFinalDraft195A.
3ChangessinceServlet3.
0PublicReview195A.
4ChangessinceServlet3.
0EDR196A.
5ChangessinceServlet2.
5MR6196A.
6ChangessinceServlet2.
5MR5196A.
6.
1ClarifySRV8.
4"TheForwardMethod"196A.
6.
2UpdateDeploymentdescriptor"http-methodvaluesallowed"197A.
6.
3ClarifySRV7.
7.
1"ThreadingIssues"197A.
7ChangesSinceServlet2.
5MR2198A.
7.
1UpdatedAnnotationRequirementsforJavaEEcontainers198A.
7.
2UpdatedJavaEnterpriseEditionRequirements198A.
7.
3ClarifiedHttpServletRequest.
getRequestURL()198A.
7.
4RemovalofIllegalStateExceptionfromHttpSession.
getId()198A.
7.
5ServletContext.
getContextPath()199A.
7.
6Requirementforweb.
xmlinwebapplications199A.
8ChangesSinceServlet2.
4200A.
8.
1SessionClarification200A.
8.
2FilterAllDispatches200A.
8.
3MultipleOccurrencesofServletMappings201ContentsxixA.
8.
4MultipleOccurrencesFilterMappings201A.
8.
5SupportAlternativeHTTPMethodswithAuthorizationConstraints202A.
8.
6MinimumJ2SERequirement203A.
8.
7AnnotationsandResourceInjection203A.
8.
8SRV.
9.
9("ErrorHandling")RequirementRemoved204A.
8.
9HttpServletRequest.
isRequestedSessionIdValid()Clarification204A.
8.
10SRV.
5.
5("ClosureofResponseObject")Clarification204A.
8.
11ServletRequest.
setCharacterEncoding()Clarified205A.
8.
12JavaEnterpriseEditionRequirements205A.
8.
13Servlet2.
4MRChangeLogUpdatesAdded205A.
8.
14SynchronizedAccessSessionObjectClarified205A.
9ChangesSinceServlet2.
3205xxJavaServletSpecification1CHAPTER1Overview1.
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-178andSection15.
3.
1,"PropagationofSecurityIdentityinEJBCalls"onpage15-180areavailableonlytothreadsexecutingtheinitialrequestorwhentherequestisdispatchedtothecontainerviatheAsyncContext.
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-98.
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)methodforallinstancesoftheAsyncListenerregisteredwiththeServletRequestforwhichtheAsyncContextwascreatedandmakethecaughtThrowableavailableviatheAsyncEvent.
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-48respectively.
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-68.
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'scontextInitializedmethodwasneitherdeclaredinweb.
xmlorweb-fragment.
xmlnorannotatedwith@WebListenerthenanUnsupportedOperationExceptionMUSTbethrownforallthemethodsdefinedforprogrammaticconfigurationofservlets,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,willonlybesupportedwhenthecomponentisaManagedBean.
FordetailsaboutwhatisaManagedBeanpleaserefertotheManagedBeanspecificationdefinedaspartofJavaEE6andJSR299.
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.
4.
8ReloadingConsiderationsAlthoughaContainerProviderimplementationofaclassreloadingschemeforeaseofdevelopmentisnotrequired,anysuchimplementationmustensurethatallservlets,andclassesthattheymayuse2,areloadedinthescopeofasingleclassloader.
ThisrequirementisneededtoguaranteethattheapplicationwillbehaveasexpectedbytheDeveloper.
Asadevelopmentaid,thefullsemanticsofnotificationtosessionbindinglistenersshouldbesupportedbycontainersforuseinthemonitoringofsessionterminationuponclassreloading.
Previousgenerationsofcontainerscreatednewclassloaderstoloadaservlet,distinctfromclassloadersusedtoloadotherservletsorclassesusedintheservletcontext.
Thiscouldcauseobjectreferenceswithinaservletcontexttopointatunexpectedclassesorobjects,andcauseunexpectedbehavior.
Therequirementisneededtopreventproblemscausedbydemandgenerationofnewclassloaders.
4.
8.
1TemporaryWorkingDirectoriesAtemporarystoragedirectoryisrequiredforeachservletcontext.
Servletcontainersmustprovideaprivatetemporarydirectoryforeachservletcontext,andmakeitavailableviathejavax.
servlet.
context.
tempdircontextattribute.
Theobjectsassociatedwiththeattributemustbeoftypejava.
io.
File.
Therequirementrecognizesacommonconvenienceprovidedinmanyservletengineimplementations.
Thecontainerisnotrequiredtomaintainthecontentsofthetemporarydirectorywhentheservletcontainerrestarts,butisrequiredtoensurethatthecontentsofthetemporarydirectoryofoneservletcontextisnotvisibletotheservletcontextsofotherWebapplicationsrunningontheservletcontainer.
2.
Anexceptionissystemclassesthattheservletmayuseinadifferentclassloader.
43CHAPTER5TheResponseTheresponseobjectencapsulatesallinformationtobereturnedfromtheservertotheclient.
IntheHTTPprotocol,thisinformationistransmittedfromtheservertotheclienteitherbyHTTPheadersorthemessagebodyoftherequest.
5.
1BufferingAservletcontainerisallowed,butnotrequired,tobufferoutputgoingtotheclientforefficiencypurposes.
Typicallyserversthatdobufferingmakeitthedefault,butallowservletstospecifybufferingparameters.
ThefollowingmethodsintheServletResponseinterfaceallowaservlettoaccessandsetbufferinginformation:getBufferSizesetBufferSizeisCommittedresetresetBufferflushBufferThesemethodsareprovidedontheServletResponseinterfacetoallowbufferingoperationstobeperformedwhethertheservletisusingaServletOutputStreamoraWriter.
ThegetBufferSizemethodreturnsthesizeoftheunderlyingbufferbeingused.
Ifnobufferingisbeingused,thismethodmustreturntheintvalueof0(zero).
TheservletcanrequestapreferredbuffersizebyusingthesetBufferSizemethod.
Thebufferassignedisnotrequiredtobethesizerequestedbytheservlet,butmustbeatleastaslargeasthesizerequested.
Thisallowsthecontainertoreuseasetoffixedsizebuffers,providingalargerbufferthanrequestedifappropriate.
The44JavaServletSpecificationmethodmustbecalledbeforeanycontentiswrittenusingaServletOutputStreamorWriter.
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:setIntHeadersetDateHeaderaddIntHeaderaddDateHeaderChapter5TheResponse45Tobesuccessfullytransmittedbacktotheclient,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.
46JavaServletSpecificationAlongwiththeWriteListener,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.
Chapter5TheResponse47Ifdatahasbeenwrittentotheresponsebuffer,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_JIS48JavaServletSpecification5.
6ClosureofResponseObjectWhenaresponseisclosed,thecontainermustimmediatelyflushallremainingcontentintheresponsebuffertotheclient.
Thefollowingeventsindicatethattheservlethassatisfiedtherequestandthattheresponseobjectistobeclosed:Theterminationoftheservicemethodoftheservlet.
TheamountofcontentspecifiedinthesetContentLengthorsetContentLengthLongmethodoftheresponsehasbeengreaterthanzeroandhasbeenwrittentotheresponse.
ThesendErrormethodiscalled.
ThesendRedirectmethodiscalled.
ThecompletemethodonAsyncContextiscalled.
5.
7LifetimeoftheResponseObjectEachresponseobjectisvalidonlywithinthescopeofaservlet'sservicemethod,orwithinthescopeofafilter'sdoFiltermethod,unlesstheassociatedrequestobjecthasasynchronousprocessingenabledforthecomponent.
Ifasynchronousprocessingontheassociatedrequestisstarted,thentherequestobjectremainsvaliduntilcompletemethodonAsyncContextiscalled.
Containerscommonlyrecycleresponseobjectsinordertoavoidtheperformanceoverheadofresponseobjectcreation.
ThedevelopermustbeawarethatmaintainingreferencestoresponseobjectsforwhichstartAsynconthecorrespondingrequesthasnotbeencalled,outsidethescopedescribedabovemayleadtonon-deterministicbehavior.
49CHAPTER6FilteringFiltersareJavacomponentsthatallowontheflytransformationsofpayloadandheaderinformationinboththerequestintoaresourceandtheresponsefromaresourceThischapterdescribestheJavaServletv.
3.
0APIclassesandmethodsthatprovidealightweightframeworkforfilteringactiveandstaticcontent.
ItdescribeshowfiltersareconfiguredinaWebapplication,andconventionsandsemanticsfortheirimplementation.
APIdocumentationforservletfiltersisprovidedonline.
TheconfigurationsyntaxforfiltersisgivenbythedeploymentdescriptorschemainChapter14,"DeploymentDescriptor".
Thereadershouldusethesesourcesasreferenceswhenreadingthischapter.
6.
1WhatisafilterAfilterisareusablepieceofcodethatcantransformthecontentofHTTPrequests,responses,andheaderinformation.
Filtersdonotgenerallycreatearesponseorrespondtoarequestasservletsdo,rathertheymodifyoradapttherequestsforaresource,andmodifyoradaptresponsesfromaresource.
Filterscanactondynamicorstaticcontent.
Forthepurposesofthischapter,dynamicandstaticcontentarereferredtoasWebresources.
Amongthetypesoffunctionalityavailabletothedeveloperneedingtousefiltersarethefollowing:Theaccessingofaresourcebeforearequesttoitisinvoked.
Theprocessingoftherequestforaresourcebeforeitisinvoked.
Themodificationofrequestheadersanddatabywrappingtherequestincustomizedversionsoftherequestobject.
50JavaServletSpecificationThemodificationofresponseheadersandresponsedatabyprovidingcustomizedversionsoftheresponseobject.
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.
ThefiltermaythrowanexceptiontoChapter6Filtering51indicatethatitcannotfunctionproperly.
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.
52JavaServletSpecification7.
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.
Chapter6Filtering536.
2.
4ConfigurationofFiltersinaWebApplicationAfilterisdefinedeitherviathe@WebFilterannotationasdefinedinSection8.
1.
2,"@WebFilter"onpage8-67ofthespecificationorinthedeploymentdescriptorusingtheelement.
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/*54JavaServletSpecificationWhenprocessingaelementusingthestyle,thecontainermustdeterminewhetherthematchestherequestURIusingthepathmappingrulesdefinedinChapter12,"MappingRequeststoServlets".
TheorderthecontainerusesinbuildingthechainoffilterstobeappliedforaparticularrequestURIisasfollows:1.
First,thematchingfiltermappingsinthesameorderthattheseelementsappearinthedeploymentdescriptor.
2.
Next,thematchingfiltermappingsinthesameorderthattheseelementsappearinthedeploymentdescriptor.
Ifafiltermappingcontainsbothand,thecontainermustexpandthefiltermappingintomultiplefiltermappings(oneforeachand),preservingtheorderoftheandelements.
Forexample,thefollowingfiltermapping:MultipeMappingsFilter/foo/*Servlet1Servlet2/bar/*Chapter6Filtering55isequivalentto:Therequirementabouttheorderofthefilterchainmeansthatthecontainer,whenreceivinganincomingrequest,processestherequestasfollows:IdentifiesthetargetWebresourceaccordingtotherulesof"SpecificationofMappings"onpage120.
IftherearefiltersmatchedbyservletnameandtheWebresourcehasa,thecontainerbuildsthechainoffiltersmatchingintheorderdeclaredinthedeploymentdescriptor.
ThelastfilterinthischaincorrespondstothelastmatchingfilterandisthefilterthatinvokesthetargetWebresource.
IftherearefiltersusingmatchingandthematchestherequestURIaccordingtotherulesofSection12.
2,"SpecificationofMappings",thecontainerbuildsthechainofmatchedfiltersinthesameorderasdeclaredinthedeploymentdescriptor.
ThelastfilterinthischainisthelastmatchingfilterinthedeploymentdescriptorforthisrequestURI.
Thelastfilterinthischainisthefilterthatinvokesthefirstfilterinthematchingchain,orinvokesthetargetWebresourceiftherearenone.
ItisexpectedthathighperformanceWebcontainerswillcachefilterchainssothattheydonotneedtocomputethemonaper-requestbasis.
MultipeMappingsFilter/foo/*MultipeMappingsFilterServlet1MultipeMappingsFilterServlet2MultipeMappingsFilter/bar/*56JavaServletSpecification6.
2.
5FiltersandtheRequestDispatcherNewsinceversion2.
4oftheJavaServletspecificationistheabilitytoconfigurefilterstobeinvokedunderrequestdispatcherforward()andinclude()calls.
Byusingthenewelementinthedeploymentdescriptor,thedevelopercanindicateforafilter-mappingwhetherhewouldlikethefiltertobeappliedtorequestswhen:1.
Therequestcomesdirectlyfromtheclient.
ThisisindicatedbyaelementwithvalueREQUEST,orbytheabsenceofanyelements.
2.
TherequestisbeingprocessedunderarequestdispatcherrepresentingtheWebcomponentmatchingtheorusingaforward()call.
ThisisindicatedbyaelementwithvalueFORWARD.
3.
TherequestisbeingprocessedunderarequestdispatcherrepresentingtheWebcomponentmatchingtheorusinganinclude()call.
ThisisindicatedbyaelementwithvalueINCLUDE.
4.
Therequestisbeingprocessedwiththeerrorpagemechanismspecifiedin"ErrorHandling"onpage106toanerrorresourcematchingthe.
ThisisindicatedbyaelementwiththevalueERROR.
5.
Therequestisbeingprocessedwiththeasynccontextdispatchmechanismspecifiedin"Asynchronousprocessing"onpage10toawebcomponentusingadispatchcall.
ThisisindicatedbyaelementwiththevalueASYNC.
6.
Oranycombinationof1,2,3,4or5above.
Forexample:LoggingFilter/products/*Chapter6Filtering57wouldresultintheLoggingFilterbeinginvokedbyclientrequestsstarting/products/.
.
.
butnotunderneatharequestdispatchercallwheretherequestdispatcherhaspathcommencing/products/.
.
.
.
TheLoggingFilterwouldbeinvokedbothontheinitialdispatchoftherequestandonresumedrequest.
Thefollowingcode:wouldresultintheLoggingFilternotbeinginvokedbyclientrequeststotheProductServlet,norunderneatharequestdispatcherforward()calltotheProductServlet,butwouldbeinvokedunderneatharequestdispatcherinclude()callwheretherequestdispatcherhasanamecommencingProductServlet.
Thefollowingcode:wouldresultintheLoggingFilterbeinginvokedbyclientrequestsstarting/products/.
.
.
andunderneatharequestdispatcherforward()callwheretherequestdispatcherhaspathcommencing/products/.
.
.
.
Finally,thefollowingcodeusesthespecialservletname'*':ThiscodewouldresultintheAllDispatchFilterbeinginvokedonrequestdispatcherforward()callsforallrequestdispatchersobtainedbynameorbypath.
LoggingFilterProductServletINCLUDELoggingFilter/products/*FORWARDREQUESTAllDispatchFilter*FORWARD58JavaServletSpecification59CHAPTER7SessionsTheHypertextTransferProtocol(HTTP)isbydesignastatelessprotocol.
TobuildeffectiveWebapplications,itisimperativethatrequestsfromaparticularclientbeassociatedwitheachother.
Manystrategiesforsessiontrackinghaveevolvedovertime,butallaredifficultortroublesomefortheprogrammertousedirectly.
ThisspecificationdefinesasimpleHttpSessioninterfacethatallowsaservletcontainertouseanyofseveralapproachestotrackauser'ssessionwithoutinvolvingtheApplicationDeveloperinthenuancesofanyoneapproach.
7.
1SessionTrackingMechanismsThefollowingsectionsdescribeapproachestotrackingauser'ssessions7.
1.
1CookiesSessiontrackingthroughHTTPcookiesisthemostusedsessiontrackingmechanismandisrequiredtobesupportedbyallservletcontainers.
Thecontainersendsacookietotheclient.
Theclientwillthenreturnthecookieoneachsubsequentrequesttotheserver,unambiguouslyassociatingtherequestwithasession.
ThestandardnameofthesessiontrackingcookiemustbeJSESSIONID,whichmustbesupportedbyall3.
0compliantcontainers.
Containersmayallowthenameofthesessiontrackingcookietobecustomizedthroughcontainerspecificconfiguration.
AllservletcontainersMUSTprovideanabilitytoconfigurewhetherornotthecontainermarksthesessiontrackingcookieasHttpOnly.
Theestablishedconfigurationmustapplytoallcontextsforwhichacontextspecificconfigurationhasnotbeenestablished(seeSessionCookieConfigjavadocformoredetails).
60JavaServletSpecificationIfawebapplicationconfiguresacustomnameforitssessiontrackingcookies,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.
AclientjoinsasessionwhensessionChapter7Sessions61trackinginformationhasbeenreturnedtotheserverindicatingthatasessionhasbeenestablished.
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.
62JavaServletSpecification7.
4BindingAttributesintoaSessionAservletcanbindanobjectattributeintoanHttpSessionimplementationbyname.
AnyobjectboundintoasessionisavailabletoanyotherservletthatbelongstothesameServletContextandhandlesarequestidentifiedasbeingapartofthesamesession.
Someobjectsmayrequirenotificationwhentheyareplacedinto,orremovedfrom,asession.
ThisinformationcanbeobtainedbyhavingtheobjectimplementtheHttpSessionBindingListenerinterface.
Thisinterfacedefinesthefollowingmethodsthatwillsignalanobjectbeingboundinto,orbeingunboundfrom,asession.
valueBoundvalueUnboundThevalueBoundmethodmustbecalledbeforetheobjectismadeavailableviathegetAttributemethodoftheHttpSessioninterface.
ThevalueUnboundmethodmustbecalledaftertheobjectisnolongeravailableviathegetAttributemethodoftheHttpSessioninterface.
7.
5SessionTimeoutsIntheHTTPprotocol,thereisnoexplicitterminationsignalwhenaclientisnolongeractive.
Thismeansthattheonlymechanismthatcanbeusedtoindicatewhenaclientisnolongeractiveisatimeoutperiod.
ThedefaulttimeoutperiodforsessionsisdefinedbytheservletcontainerandcanbeobtainedviathegetMaxInactiveIntervalmethodoftheHttpSessioninterface.
ThistimeoutcanbechangedbytheDeveloperusingthesetMaxInactiveIntervalmethodoftheHttpSessioninterface.
Thetimeoutperiodsusedbythesemethodsaredefinedinseconds.
Bydefinition,ifthetimeoutperiodforasessionissetto0orlesservalue,thesessionwillneverexpire.
Thesessioninvalidationwillnottakeeffectuntilallservletsusingthatsessionhaveexitedtheservicemethod.
Oncethesessioninvalidationisinitiated,anewrequestmustnotbeabletoseethatsession.
Chapter7Sessions637.
6LastAccessedTimesThegetLastAccessedTimemethodoftheHttpSessioninterfaceallowsaservlettodeterminethelasttimethesessionwasaccessedbeforethecurrentrequest.
Thesessionisconsideredtobeaccessedwhenarequestthatispartofthesessionisfirsthandledbytheservletcontainer.
7.
7ImportantSessionSemantics7.
7.
1ThreadingIssuesMultipleservletsexecutingrequestthreadsmayhaveactiveaccesstothesamesessionobjectatthesametime.
Thecontainermustensurethatmanipulationofinternaldatastructuresrepresentingthesessionattributesisperformedinathreadsafemanner.
TheDeveloperhastheresponsibilityforthreadsafeaccesstotheattributeobjectsthemselves.
ThiswillprotecttheattributecollectioninsidetheHttpSessionobjectfromconcurrentaccess,eliminatingtheopportunityforanapplicationtocausethatcollectiontobecomecorrupted.
7.
7.
2DistributedEnvironmentsWithinanapplicationmarkedasdistributable,allrequeststhatarepartofasessionmustbehandledbyoneJVMatatime.
ThecontainermustbeabletohandleallobjectsplacedintoinstancesoftheHttpSessionclassusingthesetAttributeorputValuemethodsappropriately.
Thefollowingrestrictionsareimposedtomeettheseconditions:ThecontainermustacceptobjectsthatimplementtheSerializableinterface.
ThecontainermaychoosetosupportstorageofotherdesignatedobjectsintheHttpSession,suchasreferencestoEnterpriseJavaBeanscomponentsandtransactions.
Migrationofsessionswillbehandledbycontainer-specificfacilities.
ThedistributedservletcontainermustthrowanIllegalArgumentExceptionforobjectswherethecontainercannotsupportthemechanismnecessaryformigrationofthesessionstoringthem.
64JavaServletSpecificationThedistributedservletcontainermustsupportthemechanismnecessaryformigratingobjectsthatimplementSerializable.
TheserestrictionsmeanthattheDeveloperisensuredthattherearenoadditionalconcurrencyissuesbeyondthoseencounteredinanon-distributedcontainer.
TheContainerProvidercanensurescalabilityandqualityofservicefeatureslikeload-balancingandfailoverbyhavingtheabilitytomoveasessionobject,anditscontents,fromanyactivenodeofthedistributedsystemtoadifferentnodeofthesystem.
Ifdistributedcontainerspersistormigratesessionstoprovidequalityofservicefeatures,theyarenotrestrictedtousingthenativeJVMSerializationmechanismforserializingHttpSessionsandtheirattributes.
DevelopersarenotguaranteedthatcontainerswillcallreadObjectandwriteObjectmethodsonsessionattributesiftheyimplementthem,butareguaranteedthattheSerializableclosureoftheirattributeswillbepreserved.
ContainersmustnotifyanysessionattributesimplementingtheHttpSessionActivationListenerduringmigrationofasession.
Theymustnotifylistenersofpassivationpriortoserializationofasession,andofactivationafterdeserializationofasession.
ApplicationDeveloperswritingdistributedapplicationsshouldbeawarethatsincethecontainermayruninmorethanoneJavavirtualmachine,thedevelopercannotdependonstaticvariablesforstoringanapplicationstate.
Theyshouldstoresuchstatesusinganenterprisebeanoradatabase.
7.
7.
3ClientSemanticsDuetothefactthatcookiesorSSLcertificatesaretypicallycontrolledbytheWebbrowserprocessandarenotassociatedwithanyparticularwindowofthebrowser,requestsfromallwindowsofaclientapplicationtoaservletcontainermightbepartofthesamesession.
Formaximumportability,theDevelopershouldalwaysassumethatallwindowsofaclientareparticipatinginthesamesession.
65CHAPTER8AnnotationsandpluggabilityThischaptertalksabouttheannotationsdefinedinServlet3.
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.
TheurlPatternsorthevalueattributeontheannotationMUSTbe66JavaServletSpecificationpresent.
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){}}Chapter8Annotationsandpluggability678.
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.
ServletRequestAttributeListener68JavaServletSpecificationjavax.
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-183willcontinuetoworkinthecontextofthesenewannotations.
Bydefaultallapplicationswillhaveindex.
htm(l)andindex.
jspinthelistofwelcome-file-list.
Thedescriptormaytobeusedtooverridethesedefaultsettings.
Chapter8Annotationsandpluggability69TheorderinwhichtheListeners,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.
70JavaServletSpecificationIfaframeworkwantsitsMETA-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.
Chapter8Annotationsandpluggability718.
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.
72JavaServletSpecification2.
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.
xmlChapter8Annotationsandpluggability73.
.
.
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.
74JavaServletSpecificationIftheruntimediscoverscircularreferences,aninformativemessagemustbelogged,andtheapplicationmustfailtodeploy.
Again,onecourseofactiontheusermaytakeistouseabsoluteorderingintheweb.
xml.
Thepreviousexamplecanbeextendedtoillustratethecasewhentheweb.
xmlcontainsanorderingsection.
web.
xmlMyFragment3MyFragment2.
.
.
Inthisexample,theorderingforthevariouselementswillbeweb.
xmlMyFragment3MyFragment2Someadditionalexamplescenariosareincludedbelow.
AlloftheseapplytorelativeorderingandnotabsoluteorderingDocumentA:CDocumentBDocumentC:Chapter8Annotationsandpluggability75DocumentD:noorderingDocumentE:noorderingDocumentF:BResultingparseorder:web.
xml,F,B,D,E,C,A.
Document:CDocumentB:DocumentC:noorderingDocumentD:DocumentE:76JavaServletSpecificationDocumentF: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,whenusingChapter8Annotationsandpluggability77annotationstodefinethelisteners,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.
78JavaServletSpecification5.
Ifmetadata-completeisnotspecifiedinthedescriptors,orissettofalseinthedeploymentdescriptor,thentheeffectivemetadatafortheapplicationisderivedbycombiningthemetadatapresentintheannotationsandthedescriptors.
Therulesformergingarespecifiedbelow-a.
Configurationsettingsinwebfragmentsareusedtoaugmentthosespecifiedinthemainweb.
xmlinsuchawayasiftheyhadbeenspecifiedinthesameweb.
xml.
b.
Theorderinwhichconfigurationsettingsofwebfragmentsareaddedtothoseinthemainweb.
xmlisasspecifiedaboveinSection8.
2.
2,"Orderingofweb.
xmlandweb-fragment.
xml"onpage8-71c.
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.
Chapter8Annotationsandpluggability79ii.
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-80JavaServletSpecificationfragment'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.
Chapter8Annotationsandpluggability81Ifaresourcereferenceannotationisusedonafielditisequivalenttodefiningtheinjection-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.
classbazTheeffectivemetadatawouldbe82JavaServletSpecification.
.
.
.
com.
foo.
Bar.
classbazCODEEXAMPLE8-5web.
xml.
.
.
Fragment1web-fragment.
xml.
.
.
com.
foo.
Bar.
classbazFragment2web-fragment.
xmlChapter8Annotationsandpluggability83.
.
.
com.
foo.
Bar2.
classbaz2Theeffectivemetadatawouldbe.
.
.
.
com.
foo.
Bar.
classbazcom.
foo.
Bar2.
classbaz284JavaServletSpecificationCODEEXAMPLE8-6web.
xmlcom.
foo.
Bar3.
classbaz3.
.
.
Fragment1web-fragment.
xml.
.
.
com.
foo.
Bar.
classbazFragment2web-fragment.
xml.
.
.
Chapter8Annotationsandpluggability85com.
foo.
Bar2.
classbaz2Theeffectivemetadatawouldbecom.
foo.
Bar3.
classbaz3com.
foo.
Bar.
classbazcom.
foo.
Bar2.
classbaz2.
.
.
86JavaServletSpecificationThefromfragment1and2willbemergedintothemainweb.
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).
Chapter8Annotationsandpluggability87vi.
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.
FooFumbbb22288JavaServletSpecificationFoo/foo/*Fum/fum/*Sincethenameoftheservletdeclaredviatheannotationdoesnotmatchthenameoftheservletdeclaredintheweb.
xml,theannotationspecifiesanewservletdeclarationinadditiontotheotherdeclarationsinweb.
xmlandisequivalentto:com.
acme.
Foocom.
acme.
Fooccc333Iftheaboveweb.
xmlwerereplacedwiththefollowingcom.
acme.
Foocom.
acme.
Fooaaa111com.
acme.
Foo/foo/*Thentheeffectivedescriptorwouldbeequivalenttocom.
acme.
FooChapter8Annotationsandpluggability89com.
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.
TheHandlesTypesannotationontheimplementationoftheServletContainerInitializerisusedtoexpressinterestinclassesthatmayhaveanotations(type,methodorfieldlevelannotations)specifiedinthevalueoftheHandlesTypesorifitextends/implementsonethoseclassesanywhereintheclass'supertypes.
TheHandlesTypesannotationisappliedirrespectiveofthesettingofmetadata-complete.
ThecontainerusestheHandlesTypesannotationtodeterminewhentoinvoketheinitializer'sonStartupmethod.
Whenexamining90JavaServletSpecificationtheclassesofanapplicationtoseeiftheymatchanyofthecriteriaspecifiedbytheHandlesTypesannotationofaServletContainerInitializer,thecontainermayrunintoclassloadingproblemsifoneormoreoftheapplication'soptionalJARfilesaremissing.
Sincethecontainerisnotinapositiontodecidewhetherthesetypesofclassloadingfailureswillpreventtheapplicationfromworkingcorrectly,itmustignorethem,whileatthesametimeprovidingaconfigurationoptionthatwouldlogthem.
IfanimplementationofServletContainerInitializerdoesnothavethe@HandlesTypesannotation,oriftherearenomatchestoanyoftheHandlesTypespecified,thenitwillgetinvokedonceforeveryapplicationwithnullasthevalueoftheSet.
Thiswillallowfortheinitializertodeterminebasedontheresourcesavailableintheapplicationwhetheritneedstoinitializeaservlet/filterornot.
TheonStartupmethodoftheServletContainerInitializerwillbeinvokedwhentheapplicationiscomingupbeforeanyofthelistener'seventsarefired.
TheServletContainerInitializer'sonStartupmethodget'saSetofClassesthateitherextend/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");}Chapter8Annotationsandpluggability91TheframeworkjarfilecanalsobebundledinWEB-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.
92JavaServletSpecificationInaddition,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.
0noyes93CHAPTER9DispatchingRequestsWhenbuildingaWebapplication,itisoftenusefultoforwardprocessingofarequesttoanotherservlet,ortoincludetheoutputofanotherservletintheresponse.
TheRequestDispatcherinterfaceprovidesamechanismtoaccomplishthis.
Whenasynchronousprocessingisenabledontherequest,theAsyncContextallowsausertodispatchtherequestbacktotheservletcontainer.
9.
1ObtainingaRequestDispatcherAnobjectimplementingtheRequestDispatcherinterfacemaybeobtainedfromtheServletContextviathefollowingmethods:getRequestDispatchergetNamedDispatcherThegetRequestDispatchermethodtakesaStringargumentdescribingapathwithinthescopeoftheServletContext.
ThispathmustberelativetotherootoftheServletContextandbeginwitha'/',orbeempty.
Themethodusesthepathtolookupaservlet,usingtheservletpathmatchingrulesinChapter12,"MappingRequeststoServlets",wrapsitwithaRequestDispatcherobject,andreturnstheresultingobject.
Ifnoservletcanberesolvedbasedonthegivenpath,aRequestDispatcherisprovidedthatreturnsthecontentforthatpath.
ThegetNamedDispatchermethodtakesaStringargumentindicatingthenameofaservletknowntotheServletContext.
Ifaservletisfound,itiswrappedwithaRequestDispatcherobjectandtheobjectisreturned.
Ifnoservletisassociatedwiththegivenname,themethodmustreturnnull.
94JavaServletSpecificationToallowRequestDispatcherobjectstobeobtainedusingrelativepathsthatarerelativetothepathofthecurrentrequest(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);Chapter9DispatchingRequests959.
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_string96JavaServletSpecificationIftheincludedservletwasobtainedbyusingthegetNamedDispatchermethod,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.
Chapter9DispatchingRequests97Thefollowingrequestattributesmustbeset: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_string98JavaServletSpecification9.
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.
Chapter9DispatchingRequests99Thefollowingrequestattributesmustbeset: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_string100JavaServletSpecification101CHAPTER10WebApplicationsAWebapplicationisacollectionofservlets,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.
102JavaServletSpecification10.
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.
Chapter10WebApplications103path.
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.
104JavaServletSpecification10.
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.
classChapter10WebApplications105MIMETypeMappingsWelcomeFilelistErrorPagesSecurity10.
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.
Thecontainer106JavaServletSpecificationshouldnotallowapplicationstooverrideoraccessthecontainer'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.
Chapter10WebApplications107TherequestattributesinTABLE10-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.
String108JavaServletSpecificationTheWebapplicationmayhavedeclarederrorpagesusingtheexception-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-16Chapter10WebApplications10910.
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:110JavaServletSpecificationThedeploymentdescriptorliststhefollowingwelcomefiles.
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.
jspChapter10WebApplications111EnvironmentandtheJavaEEspecification.
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.
112JavaServletSpecification113CHAPTER11ApplicationLifecycleEvents11.
1IntroductionTheapplicationeventsfacilitygivestheWebApplicationDevelopergreatercontroloverthelifecycleoftheServletContextandHttpSessionandServletRequest,allowsforbettercodefactorization,andincreasesefficiencyinmanagingtheresourcesthattheWebapplicationuses.
11.
2EventListenersApplicationeventlistenersareclassesthatimplementoneormoreoftheservleteventlistenerinterfaces.
TheyareinstantiatedandregisteredintheWebcontaineratthetimeofthedeploymentoftheWebapplication.
TheyareprovidedbytheDeveloperintheWAR.
ServleteventlistenerssupporteventnotificationsforstatechangesintheServletContext,HttpSessionandServletRequestobjects.
ServletcontextlistenersareusedtomanageresourcesorstateheldataJVMlevelfortheapplication.
HTTPsessionlistenersareusedtomanagestateorresourcesassociatedwithaseriesofrequestsmadeintoaWebapplicationfromthesameclientoruser.
Servletrequestlistenersareusedtomanagestateacrossthelifecycleofservletrequests.
Asynclistenersareusedtomanageasynceventssuchastimeoutsandcompletionofasyncprocessing.
Theremaybemultiplelistenerclasseslisteningtoeacheventtype,andtheDevelopermayspecifytheorderinwhichthecontainerinvokesthelistenerbeansforeacheventtype.
114JavaServletSpecification11.
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.
httpHttpSessionBindingListenerChapter11ApplicationLifecycleEvents115FordetailsoftheAPI,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.
AsyncListener116JavaServletSpecification11.
3.
2DeploymentDeclarationsListenerclassesaredeclaredintheWebapplicationdeploymentdescriptorusingthelistenerelement.
Theyarelistedbyclassnameintheorderinwhichtheyaretobeinvoked.
Unlikeotherlisteners,listenersoftypeAsyncListenermayonlyberegistered(withaServletRequest)programmatically.
11.
3.
3ListenerRegistrationTheWebcontainercreatesaninstanceofeachlistenerclassandregistersitforeventnotificationspriortotheprocessingofthefirstrequestbytheapplication.
TheWebcontainerregistersthelistenerinstancesaccordingtotheinterfacestheyimplementandtheorderinwhichtheyappearinthedeploymentdescriptor.
DuringWebapplicationexecution,listenerscorrespondingtogiveneventsareinvokedintheorderoftheirregistration.
11.
3.
4NotificationsAtShutdownOnapplicationshutdown,listenersarenotifiedinreverseordertotheirdeclarationswithnotificationstosessionlistenersprecedingnotificationstocontextlisteners.
Sessionlistenersmustbenotifiedofsessioninvalidationspriortocontextlistenersbeingnotifiedofapplicationshutdown.
11.
4DeploymentDescriptorExampleThefollowingexampleisthedeploymentgrammarforregisteringtwoservletcontextlifecyclelistenersandanHttpSessionlistener.
Supposethatcom.
acme.
MyConnectionManagerandcom.
acme.
MyLoggingModulebothimplementjavax.
servlet.
ServletContextListener,andthatcom.
acme.
MyLoggingModuleadditionallyimplementsjavax.
servlet.
http.
HttpSessionListener.
Also,theDeveloperwantsChapter11ApplicationLifecycleEvents117com.
acme.
MyConnectionManagertobenotifiedofservletcontextlifecycleeventsbeforecom.
acme.
MyLoggingModule.
Hereisthedeploymentdescriptorforthisapplication:11.
5ListenerInstancesandThreadingThecontainerisrequiredtocompleteinstantiationofthelistenerclassesinaWebapplicationpriortothestartofexecutionofthefirstrequestintotheapplication.
ThecontainermustmaintainareferencetoeachlistenerinstanceuntilthelastrequestisservicedfortheWebapplication.
AttributechangestoServletContextandHttpSessionobjectsmayoccurconcurrently.
Thecontainerisnotrequiredtosynchronizetheresultingnotificationstoattributelistenerclasses.
Listenerclassesthatmaintainstateareresponsiblefortheintegrityofthedataandshouldhandlethiscaseexplicitly.
11.
6ListenerExceptionsApplicationcodeinsidealistenermaythrowanexceptionduringoperation.
Somelistenernotificationsoccurunderthecalltreeofanothercomponentintheapplication.
Anexampleofthisisaservletthatsetsasessionattribute,wherethesessionlistenerthrowsanunhandledexception.
ThecontainermustallowunhandledexceptionstobehandledbytheerrorpagemechanismdescribedinMyListeningApplicationcom.
acme.
MyConnectionManagercom.
acme.
MyLoggingModuleRegistrationServlet.
.
.
etc118JavaServletSpecificationSection10.
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.
119CHAPTER12MappingRequeststoServletsThemappingtechniquesdescribedinthischapterarerequiredforWebcontainersmappingclientrequeststoservlets.
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.
120JavaServletSpecification4.
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.
Chapter12MappingRequeststoServlets12112.
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.
bopservlet4122JavaServletSpecification123CHAPTER13SecurityWebapplicationsarecreatedbyApplicationDeveloperswhogive,sell,orotherwisetransfertheapplicationtoaDeployerforinstallationintoaruntimeenvironment.
ApplicationDeveloperscommunicatethesecurityrequirementstotheDeployersandthedeploymentsystem.
Thisinformationmaybeconveyeddeclarativelyviatheapplication'sdeploymentdescriptor,orbyusingannotationswithintheapplicationcode.
ThischapterdescribestheServletcontainersecuritymechanismsandinterfacesandthedeploymentdescriptorandannotationbasedmechanismsforconveyingthesecurityrequirementsofapplications.
13.
1IntroductionAwebapplicationcontainsresourcesthatcanbeaccessedbymanyusers.
Theseresourcesoftentraverseunprotected,opennetworkssuchastheInternet.
Insuchanenvironment,asubstantialnumberofwebapplicationswillhavesecurityrequirements.
Althoughthequalityassurancesandimplementationdetailsmayvary,servletcontainershavemechanismsandinfrastructureformeetingtheserequirementsthatsharesomeofthefollowingcharacteristics:Authentication:Themeansbywhichcommunicatingentitiesprovetooneanotherthattheyareactingonbehalfofspecificidentitiesthatareauthorizedforaccess.
Accesscontrolforresources:Themeansbywhichinteractionswithresourcesarelimitedtocollectionsofusersorprogramsforthepurposeofenforcingintegrity,confidentiality,oravailabilityconstraints.
DataIntegrity:Themeansusedtoprovethatinformationhasnotbeenmodifiedbyathirdpartywhileintransit.
124JavaServletSpecificationConfidentialityorDataPrivacy:Themeansusedtoensurethatinformationismadeavailableonlytouserswhoareauthorizedtoaccessit.
13.
2DeclarativeSecurityDeclarativesecurityreferstothemeansofexpressinganapplication'ssecuritymodelorrequirements,includingroles,accesscontrol,andauthenticationrequirementsinaformexternaltotheapplication.
Thedeploymentdescriptoristheprimaryvehiclefordeclarativesecurityinwebapplications.
TheDeployermapstheapplication'slogicalsecurityrequirementstoarepresentationofthesecuritypolicythatisspecifictotheruntimeenvironment.
Atruntime,theservletcontainerusesthesecuritypolicyrepresentationtoenforceauthenticationandauthorization.
Thesecuritymodelappliestothestaticcontentpartofthewebapplicationandtoservletsandfilterswithintheapplicationthatarerequestedbytheclient.
ThesecuritymodeldoesnotapplywhenaservletusestheRequestDispatchertoinvokeastaticresourceorservletusingaforwardoraninclude.
13.
3ProgrammaticSecurityProgrammaticsecurityisusedbysecurityawareapplicationswhendeclarativesecurityaloneisnotsufficienttoexpressthesecuritymodeloftheapplication.
ProgrammaticsecurityconsistsofthefollowingmethodsoftheHttpServletRequestinterface:authenticateloginlogoutgetRemoteUserisUserInRolegetUserPrincipalTheloginmethodallowsanapplicationtoperformusernameandpasswordcollection(asanalternativetoForm-BasedLogin).
Theauthenticatemethodsallowanapplicationtoinstigateauthenticationoftherequestcallerbythecontainerfromwithinanunconstrainedrequestcontext.
Thelogoutmethodisprovidedtoallowanapplicationtoresetthecalleridentityofarequest.
Chapter13Security125ThegetRemoteUsermethodreturnsthenameoftheremoteuser(thatis,thecaller)associated,bythecontainer,withtherequest.
TheisUserInRolemethoddeterminesiftheremoteuser(thatis,thecaller)associatedwiththerequestisinaspecifiedsecurityrole.
ThegetUserPrincipalmethoddeterminestheprincipalnameoftheremoteuser(thatis,thecaller)andreturnsajava.
security.
Principalobjectcorrespondingtotheremoteuser.
CallingthegetNamemethodonthePrincipalreturnedbygetUserPrincipalreturnsthenameoftheremoteuser.
TheseAPIsallowservletstomakebusinesslogicdecisionsbasedontheinformationobtained.
Ifnouserhasbeenauthenticated,thegetRemoteUsermethodreturnsnull,theisUserInRolemethodalwaysreturnsfalse,andthegetUserPrincipalmethodreturnsnull.
TheisUserInRolemethodexpectsaStringuserrole-nameparameter.
Asecurity-role-refelementshouldbedeclaredinthedeploymentdescriptorwitharole-namesub-elementcontainingtherolenametobepassedtothemethod.
Asecurity-role-refelementshouldcontainarole-linksub-elementwhosevalueisthenameofthesecurityrolethattheusermaybemappedinto.
Thecontainerusesthemappingofsecurity-role-reftosecurity-rolewhendeterminingthereturnvalueofthecall.
Forexample,tomapthesecurityrolereference"FOO"tothesecurityrolewithrole-name"manager"thesyntaxwouldbe:Inthiscaseiftheservletcalledbyauserbelongingtothe"manager"securityrolemadetheAPIcallisUserInRole("FOO")theresultwouldbetrue.
Ifnosecurity-role-refelementmatchingasecurity-roleelementhasbeendeclared,thecontainermustdefaulttocheckingtherole-nameelementargumentagainstthelistofsecurity-roleelementsforthewebapplication.
TheisUserInRolemethodreferencesthelisttodeterminewhetherthecallerismappedtoasecurityrole.
Thedevelopermustbeawarethattheuseofthisdefaultmechanismmaylimittheflexibilityinchangingrolenamesintheapplicationwithouthavingtorecompiletheservletmakingthecall.
FOOmanager126JavaServletSpecification13.
4ProgrammaticAccessControlAnnotationsThissectiondefinestheannotationsandapisprovidedtoconfigurethesecurityconstraintsenforcedbytheServletContainer.
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();}@HttpConstraintTABLE13-1TheServletSecurityInterfaceElementDescriptionDefaultvaluetheHttpConstraintthatdefinestheprotectiontobeappliedtoallHTTPmethodsthatareNOTrepresentedinthearrayreturnedbyhttpMethodConstraints.
@HttpConstrainthttpMethodConstraintsthearrayofHTTPmethodspecificconstraints.
{}Chapter13Security127The@HttpConstraintannotationisusedwithinthe@ServletSecurityannotationtorepresentthesecurityconstrainttobeappliedtoallHTTPprotocolmethodsforwhichacorresponding@HttpMethodConstraintdoesNOToccurwithinthe@ServletSecurityannotation.
packagejavax.
servlet.
annotation;@Documented@Retention(value=RUNTIME)public@interfaceHttpConstraint{ServletSecurity.
EmptyRoleSemanticvalue();java.
lang.
String[]rolesAllowed();ServletSecurity.
TransportGuaranteetransportGuarantee();}@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.
NONE128JavaServletSpecification}The@ServletSecurityannotationmaybespecifiedon(thatis,targetedto)aServletimplementationclass,anditsvalueisinheritedbysubclassesaccordingtotherulesdefinedforthe@Inheritedmeta-annotation.
Atmostoneinstanceofthe@ServletSecurityannotationmayoccuronaServletimplementationclass,andthe@ServletSecurityannotationMUSTNOTbespecifiedon(thatis,targetedto)aJavamethod.
Whenoneormore@HttpMethodConstraintannotationsaredefinedwithina@ServletSecurityannotation,each@HttpMethodConstraintdefinesthesecurity-constraintthatappliestotheHTTPprotocolmethodidentifiedwithinthe@HttpMethodConstraint.
Theencompassing@ServletSecurityannotationdefinesthesecurity-constraintthatappliestoallHTTPprotocolmethodsotherthanthoseforwhichacorresponding@HttpMethodConstraintisdefinedwithinthe@ServletSecurityannotation.
Thesecurity-constraintelementsdefinedintheportabledeploymentdescriptorsareauthoritativeforalltheurl-patternsoccurringwithintheconstraints.
Whenasecurity-constraintintheportabledeploymentdescriptorincludesaurl-patternthatisanexactmatchforapatternmappedtoaclassannotatedwith@ServletSecurity,theannotationmusthavenoeffectontheconstraintsenforcedbytheServletcontaineronthepattern.
Whenmetadata-complete=trueisdefinedforaportabledeploymentdescriptor,the@ServletSecurityannotationdoesnotapplytoanyoftheurl-patternsmappedto(anyservletmappedto)theannotatedclassinthedeploymentdescriptor.
TABLE13-3TheHttpMethodConstraintInterfaceElementDescriptionDefaultvalueTheHTTPprotocolmethodnameemptyRoleSemanticThedefaultauthorizationsemanticthatapplies(only)whenrolesAllowedreturnsanemptyarray.
PERMITrolesAllowedAnarraycontainingthenamesoftheauthorizedroles{}transportGuaranteeThedataprotectionrequirementsthatmustbesatisfiedbytheconnectionsonwhichrequestsarrive.
NONEChapter13Security129The@ServletSecurityannotationisnotappliedtotheurl-patternsofaServletRegistrationcreatedusingtheaddServlet(String,Servlet)methodoftheServletContextinterface,unlesstheServletwasconstructedbythecreateServletmethodoftheServletContextinterface.
Withtheexceptionslistedabove,whenaServletclassisannotatedwith@ServletSecurity,theannotationdefinesthesecurityconstraintsthatapplytoalltheurl-patternsmappedtoalltheServletsmappedtotheclass.
Whenaclasshasnotbeenannotatedwiththe@ServletSecurityannotation,theaccesspolicythatisappliedtoaservletmappedfromthatclassisestablishedbytheapplicablesecurity-constraintelements,ifany,inthecorrespondingportabledeploymentdescriptor,orbarringanysuchelements,bytheconstraints,ifany,establishedprogrammaticallyforthetargetservletviathesetServletSecuritymethodoftheServletRegistrationinterface.
13.
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,confidentialtransportrequired130JavaServletSpecification@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{}CODEEXAMPLE13-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.
Chapter13Security131Thefollowingexampledepictstherepresentationofa@ServletSecurityannotationwithnocontained@HttpMethodConstraintannotationsasasinglesecurity-constraintelement.
Theurl-patternelementsdefinedbythecorrespondingservlet(registration)wouldbeincludedintheweb-resource-collection,andthepresenceandvalueofanycontainedauth-constraintanduser-data-constraintelementswouldbedeterminedbythemappingofthe@HttpConstraintvalueasdefinedinSection13.
4.
1.
3,"Mapping@HttpConstraintand@HttpMethodConstrainttoXML.
"onpage13-132CODEEXAMPLE13-8mapping@ServletSecuritywithnocontained@HttpMethodConstraint@ServletSecurity(@HttpConstraint(rolesAllowed="Role1")).
.
.
Role1Whenoneormore@HttpMethodConstraintelementsarespecified,themethod-independentconstraintcorrespondstoasinglesecurity-constraintcontainingaweb-resource-collectionthatcontainsonhttp-method-omissionelementforeachoftheHTTPmethodsnamedinthemethod-specificconstraints.
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-132CODEEXAMPLE13-9mapping@ServletSecuritywithcontained@HttpMethodConstraint@ServletSecurity(value=@HttpConstraint(rolesAllowed="Role1"),httpMethodConstraints=@HttpMethodConstraint(value="TRACE",emptyRoleSemantic=EmptyRoleSemantic.
DENY))132JavaServletSpecification.
.
.
TRACERole1.
.
.
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.
Thedefaultvalueforthiselementinanemptylist.
transportGuaranteeChapter13Security133Thedataprotectionrequirements,eitherNONEorCONFIDENTIAL,thatmustbesatisfiedbytheconnectionsonwhichrequestsarrive.
Thiselementisequivalentinmeaningtoauser-data-constraintcontainingatransport-guaranteewiththecorrespondingvalue.
ThedefaultvalueforthiselementisNONE.
Thefollowingexamplesdepictthecorrespondencebetweenthe@HttpConstraintmodeldescribedaboveandauth-constraintanduser-data-constraintelementsinweb.
xml.
CODEEXAMPLE13-10emptyRoleSemantic=PERMIT,rolesAllowed={},transportGuarantee=NONEnoconstraintsCODEEXAMPLE13-11emptyRoleSemantic=PERMIT,rolesAllowed={},transportGuarantee=CONFIDENTIALCONFIDENTIALCODEEXAMPLE13-12emptyRoleSemantic=PERMIT,rolesAllowed={Role1},transportGuarantee=NONERole1CODEEXAMPLE13-13emptyRoleSemantic=PERMIT,rolesAllowed={Role1},transportGuarantee=CONFIDENTIALRole1CONFIDENTIALCODEEXAMPLE13-14emptyRoleSemantic=DENY,rolesAllowed={},transportGuarantee=NONECODEEXAMPLE13-15emptyRoleSemantic=DENY,rolesAllowed={},transportGuarantee=CONFIDENTIALCONFIDENTIAL134JavaServletSpecification13.
4.
2setServletSecurityofServletRegistration.
DynamicThesetServletSecuritymethodmaybeusedwithinaServletContextListenertodefinethesecurityconstraintstobeappliedtothemappingsdefinedforaServletRegistration.
CollectionsetServletSecurity(ServletSecurityElementarg);Thejavax.
servlet.
ServletSecurityElementargumenttosetServletSecurityisanalogousinstructureandmodeltotheServletSecurityinterfaceofthe@ServletSecurityannotation.
Assuch,themappingsdefinedinSection13.
4.
1.
2,"Mapping@ServletSecuritytosecurity-constraint"onpage13-130,applyanalogouslytothemappingofaServletSecurityElementwithcontainedHttpConstraintElementandHttpMethodConstraintElementvalues,toitsequivalentsecurity-constraintrepresentation.
ThesetServletSecuritymethodreturnsthe(possiblyempty)SetofURLpatternsthatarealreadytheexacttargetofasecurity-constraintelementintheportabledeploymentdescriptor(andthuswereunaffectedbythecall).
ThismethodthrowsanIllegalStateExceptioniftheServletContextfromwhichtheServletRegistrationwasobtainedhasalreadybeeninitialized.
Whenasecurity-constraintintheportabledeploymentdescriptorincludesaurl-patternthatisanexactmatchforapatternmappedbyaServletRegistration,callstosetServletSecurityontheServletRegistrationmusthavenoeffectontheconstraintsenforcedbytheServletcontaineronthepattern.
WiththeexceptionslistedaboveandincludingwhentheServletclassisannotatedwith@ServletSecurity,whensetServletSecurityiscalledonaServletRegistrationitestablishesthesecurityconstraintsthatapplytotheurl-patternsoftheregistration.
13.
5RolesAsecurityroleisalogicalgroupingofusersdefinedbytheApplicationDeveloperorAssembler.
Whentheapplicationisdeployed,rolesaremappedbyaDeployertoprincipalsorgroupsintheruntimeenvironment.
Chapter13Security135Aservletcontainerenforcesdeclarativeorprogrammaticsecurityfortheprincipalassociatedwithanincomingrequestbasedonthesecurityattributesoftheprincipal.
Thismayhappenineitherofthefollowingways:1.
Adeployerhasmappedasecurityroletoausergroupintheoperationalenvironment.
Theusergroupstowhichthecallingprincipalbelongsareretrievedfromitssecurityattributes.
Theprincipalisinthesecurityroleonlyiftheprincipalbelongstotheusergrouptowhichthesecurityrolehasbeenmappedbythedeployer.
2.
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.
136JavaServletSpecification13.
6.
2HTTPDigestAuthenticationLikeHTTPBasicAuthentication,HTTPDigestAuthenticationauthenticatesauserbasedonausernameandapassword.
However,unlikeHTTPBasicAuthentication,HTTPDigestAuthenticationdoesnotsenduserpasswordsoverthenetwork.
InHTTPDigestauthenticationtheclientsendsaone-waycryptographichashofthepassword(andadditionaldata).
Althoughpasswordsarenotsentonthewire,HTTPDigestauthenticationrequiresthatcleartextpasswordequivalents1beavaialbletotheauthenticatingcontainersothatitcanvalidatereceivedauthenticatorsbycalculatingtheexpecteddigest.
ServletcontainersSHOULDtosupportHTTP_DIGESTauthentication.
13.
6.
3FormBasedAuthenticationThelookandfeelofthe"loginscreen"cannotbevariedusingthewebbrowser'sbuilt-inauthenticationmechanisms.
ThisspecificationintroducesarequiredformbasedauthenticationmechanismwhichallowsaDevelopertocontrolthelookandfeeloftheloginscreens.
Thewebapplicationdeploymentdescriptorcontainsentriesforaloginformanderrorpage.
Theloginformmustcontainfieldsforenteringausernameandapassword.
Thesefieldsmustbenamedj_usernameandj_password,respectively.
Whenauserattemptstoaccessaprotectedwebresource,thecontainercheckstheuser'sauthentication.
Iftheuserisauthenticatedandpossessesauthoritytoaccesstheresource,therequestedwebresourceisactivatedandareferencetoitisreturned.
Iftheuserisnotauthenticated,allofthefollowingstepsoccur:1.
TheloginformassociatedwiththesecurityconstraintissenttotheclientandtheURLpathtriggeringtheauthenticationisstoredbythecontainer.
2.
Theuserisaskedtofillouttheform,includingtheusernameandpasswordfields.
3.
Theclientpoststheformbacktotheserver.
4.
Thecontainerattemptstoauthenticatetheuserusingtheinformationfromtheform.
5.
Ifauthenticationfails,theerrorpageisreturnedusingeitheraforwardoraredirect,andthestatuscodeoftheresponseissetto200.
6.
Ifauthenticationsucceeds,theauthenticateduser'sprincipalischeckedtoseeifitisinanauthorizedroleforaccessingtheresource.
1.
Thepasswordequivalentscanbesuchthattheycanonlybeusedtoauthenticateastheuserataspecificrealm.
Chapter13Security1377.
Iftheuserisauthorized,theclientisredirectedtotheresourceusingthestoredURLpath.
Theerrorpagesenttoauserthatisnotauthenticatedcontainsinformationaboutthefailure.
FormBasedAuthenticationhasthesamelackofsecurityasBasicAuthenticationsincetheuserpasswordistransmittedasplaintextandthetargetserverisnotauthenticated.
Againadditionalprotectioncanalleviatesomeoftheseconcerns:asecuretransportmechanism(HTTPS),orsecurityatthenetworklevel(suchastheIPSECprotocolorVPNstrategies)isappliedinsomedeploymentscenarios.
TheloginmethodoftheHttpServletRequestinterfaceprovidesanalternativemeansforanapplicationtocontrolthelookandfeelofit'sloginscreens.
13.
6.
3.
1LoginFormNotesFormbasedloginandURLbasedsessiontrackingcanbeproblematictoimplement.
FormbasedloginshouldbeusedonlywhensessionsarebeingmaintainedbycookiesorbySSLsessioninformation.
Inorderfortheauthenticationtoproceedappropriately,theactionoftheloginformmustalwaysbej_security_check.
Thisrestrictionismadesothattheloginformwillworknomatterwhichresourceitisfor,andtoavoidrequiringtheservertospecifytheactionfieldoftheoutboundform.
HereisanexampleshowinghowtheformshouldbecodedintotheHTMLpage:IftheformbasedloginisinvokedbecauseofanHTTPrequest,theoriginalrequestparametersmustbepreservedbythecontainerforuseif,onsuccessfulauthentication,itredirectsthecalltotherequestedresource.
IftheuserisauthenticatedusingformloginandhascreatedanHTTPsession,thetimeoutorinvalidationofthatsessionleadstotheuserbeingloggedoutinthesensethatsubsequentrequestsmustcausetheusertobere-authenticated.
Thescopeofthelogoutisthesameasthatoftheauthentication:forexample,ifthecontainersupportssinglesignon,suchasJavaEEtechnologycompliantwebcontainers,theuserwouldneedtoreauthenticatewithanyofthewebapplicationshostedonthewebcontainer.
138JavaServletSpecification13.
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:1.
Makeloginmechanismsandpoliciesapropertyoftheenvironmentthewebapplicationisdeployedin.
2.
Beabletousethesameauthenticationinformationtorepresentaprincipaltoallapplicationsdeployedinthesamecontainer,and3.
Requirere-authenticationofusersonlywhenasecuritypolicydomainboundaryhasbeencrossed.
Chapter13Security139Therefore,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.
Anauthorizationconstraintthatnamesnorolesindicatesthataccesstotheconstrainedrequestsmustnotbepermittedunderanycircumstances.
Anauthorizationconstraintconsistsofthefollowingelement:rolename(role-nameindeploymentdescriptor)Auserdataconstraintestablishesarequirementthattheconstrainedrequestsbereceivedoveraprotectedtransportlayerconnection.
Thestrengthoftherequiredprotectionisdefinedbythevalueofthetransportguarantee.
AtransportguaranteeofINTEGRALisusedtoestablisharequirementforcontentintegrityandatransportguaranteeofCONFIDENTIALisusedtoestablisharequirementforconfidentiality.
Thetransportguaranteeof"NONE"indicatesthatthecontainermustaccepttheconstrainedrequestswhenreceivedonanyconnectionincludinganunprotectedone.
Auserdataconstraintconsistsofthefollowingelement:transportguarantee(transport-guaranteeindeploymentdescriptor)140JavaServletSpecificationIfnoauthorizationconstraintappliestoarequest,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.
Asecurityconstraintthatdoesnotcontainanauthorizationconstraintshallcombinewithauthorizationconstraintsthatnameorimplyrolestoallowunauthenticatedaccess.
Thespecialcaseofanauthorizationconstraintthatnamesnorolesshallcombinewithanyotherconstraintstooverridetheiraffectsandcauseaccesstobeprecluded.
Thecombinationofuser-data-constraintsthatapplytoacommonurl-patternandhttp-methodshallyieldtheunionofconnectiontypesacceptedbytheindividualconstraintsasacceptableconnectiontypes.
Asecurityconstraintthatdoesnotcontainauser-data-constraintshallcombinewithotheruser-data-constrainttocausetheunprotectedconnectiontypetobeanacceptedconnectiontype.
Chapter13Security14113.
8.
2ExampleThefollowingexampleillustratesthecombinationofconstraintsandtheirtranslationintoatableofapplicableconstraints.
Supposethatadeploymentdescriptorcontainedthefollowingsecurityconstraints.
precludedmethods/*/acme/wholesale/*/acme/retail/*GETPOSTwholesale/acme/wholesale/*GETPUTSALESCLERK142JavaServletSpecificationwholesale2/acme/wholesale/*GETPOSTCONTRACTORCONFIDENTIALretail/acme/retail/*GETPOSTCONTRACTORHOMEOWNERChapter13Security143ThetranslationofthishypotheticaldeploymentdescriptorwouldyieldtheconstraintsdefinedinTABLE13-4.
13.
8.
3ProcessingRequestsWhenaServletcontainerreceivesarequest,itshallusethealgorithmdescribedin"UseofURLPaths"onpage119toselecttheconstraints(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/*POSTCONTRACTORHOMEOWNERnotconstrained144JavaServletSpecification1.
Thecharacteristicsoftheconnectiononwhichtherequestwasreceivedmustsatisfyatleastoneofthesupportedconnectiontypesdefinedbytheconstraints.
Ifthisruleisnotsatisfied,thecontainershallrejecttherequestandredirectittotheHTTPSport.
22.
Theauthenticationcharacteristicsoftherequestmustsatisfyanyauthenticationandrolerequirementsdefinedbytheconstraints.
Ifthisruleisnotsatisfiedbecauseaccesshasbeenprecluded(byanauthorizationconstraintnamingnoroles),therequestshallberejectedasforbiddenanda403(SC_FORBIDDEN)statuscodeshallbereturnedtotheuser.
Ifaccessisrestrictedtopermittedrolesandtherequesthasnotbeenauthenticated,therequestshallberejectedasunauthorizedanda401(SC_UNAUTHORIZED)statuscodeshallbereturnedtocauseauthentication.
Ifaccessisrestrictedtopermittedrolesandtheauthenticationidentityoftherequestisnotamemberofanyoftheseroles,therequestshallberejectedasforbiddenanda403(SC_FORBIDDEN)statuscodeshallbereturnedtotheuser.
13.
9DefaultPoliciesBydefault,authenticationisnotneededtoaccessresources.
Authenticationisrequiredwhenthesecurityconstraints(ifany)thatcontaintheurl-patternthatisthebestmatchfortherequestURIcombinetoimposeanauth-constraint(namingroles)ontheHTTPmethodoftherequest.
Similarly,aprotectedtransportisnotrequiredunlessthesecurityconstraintsthatapplytotherequestcombinetoimposeauser-data-constraint(withaprotectedtransport-guarantee)ontheHTTPmethodoftherequest.
13.
10LoginandLogoutThecontainerestablishesthecalleridentityofarequestpriortodispatchingtherequesttotheservletengine.
Thecalleridentityremainsunchangedthroughouttheprocessingoftherequestoruntiltheapplicationsucessfullycallsauthenticate,loginorlogoutontherequest.
Forasynchronousrequests,thecalleridentityestablishedattheinitialdispatchremainsunchangeduntiltheprocessingoftheoverallrequestcompletes,ortheapplicationsuccessfullycallsauthenticate,loginorlogoutontherequest.
2.
Asanoptimization,acontainershouldrejecttherequestasforbiddenandreturna403(SC_FORBIDDEN)statuscodeifitknowsthataccesswillultimatelybeprecluded(byanauthorizationconstraintnamingnoroles).
Chapter13Security145Beingloggedintoanapplicationduringtheprocessingofarequest,correspondspreciselytotherebeingavalidnon-nullcalleridentityassociatedwiththerequestasmaybedeterminedbycallinggetRemoteUserorgetUserPrincipalontherequest.
Anullreturnvaluefromeitherofthesemethodsindicatesthatthecallerisnotloggedintotheapplicationwithrespecttotheprocessingoftherequest.
ContainersmaycreateHTTPSessionobjectstotrackloginstate.
Ifadevelopercreatesasessionwhileauserisnotauthenticated,andthecontainerthenauthenticatestheuser,thesessionvisibletodevelopercodeafterloginmustbethesamesessionobjectthatwascreatedpriortologinoccurringsothatthereisnolossofsessioninformation.
146JavaServletSpecification147CHAPTER14DeploymentDescriptorThischapterspecifiestheJavaServletSpecificationversion3.
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:ServletContextInitParametersSessionConfigurationServletDeclarationServletMappingsApplicationLifecyleListenerclassesFilterDefinitionsandFilterMappingsMIMETypeMappingsWelcomeFilelistErrorPagesLocaleandEncodingMappings148JavaServletSpecificationSecurityconfiguration,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.
Chapter14DeploymentDescriptor149Containersmustattempttocanonicalizepathsinthedeploymentdescriptor.
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-appElement150JavaServletSpecificationTheweb-appelementistherootdeploymentdescriptorforaWebapplication.
Thiselementcontainsthefollowingelements.
Thiselementhasarequiredattributeversiontospecifytowhichversionoftheschemathedeploymentdescriptorconforms.
Allsubelementsunderthiselementcanbeinanarbitraryorder.
FIGURE14-1web-appElementStructureChapter14DeploymentDescriptor1512.
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.
The152JavaServletSpecificationinit-paramelementcontainsname-valuepairasaninitializationparameterofthisfilter.
Theoptionalasync-supportedelement,whenspecified,indicatesthatthefiltersupportsasynchronousrequestprocessing.
FIGURE14-2filterElementStructure8.
filter-mappingElementChapter14DeploymentDescriptor153Thefilter-mappingisusedbythecontainertodecidewhichfilterstoapplytoarequestinwhatorder.
Thevalueofthefilter-namemustbeoneofthefilterdeclarationsinthedeploymentdescriptor.
Thematchingrequestcanbespecifiedeitherurl-patternorservlet-name.
FIGURE14-3filter-mappingElementStructure9.
listenerElementThelistenerindicatesthedeploymentpropertiesforanapplicationlistenerbean.
Thesub-elementlistener-classdeclaresthataclassintheapplicationmustberegisteredasaWebapplicationlistenerbean.
Thevalueisthefullyqualifiedclassnameofthelistenerclass.
FIGURE14-4listenerElementStructure154JavaServletSpecification10.
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.
TheChapter14DeploymentDescriptor155multipart-configelementcanbeusedtospecifythelocationwherethefilescanbestored,maximumsizeofthefilebeinguploaded,maximumrequestsizeandthesizethresholdafterwhichthefilewillbewrittentothedisk.
FIGURE14-5servletElementStructure156JavaServletSpecification11.
servlet-mappingElementTheservlet-mappingdefinesamappingbetweenaservletandaURLpattern.
FIGURE14-6servlet-mappingElementStructure12.
session-configElementThesession-configdefinesthesessionparametersforthisWebapplication.
Thesub-elementsession-timeoutdefinesthedefaultsessiontimeoutintervalforallsessionscreatedinthisWebapplication.
Thespecifiedtimeoutmustbeexpressedinawholenumberofminutes.
Ifthetimeoutis0orless,thecontainerensuresthedefaultbehaviorofsessionsisnevertotimeout.
Ifthiselementisnotspecified,thecontainermustsetitsdefaulttimeoutperiod.
FIGURE14-7session-configElementStructure13.
mime-mappingElementChapter14DeploymentDescriptor157Themime-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-typecontainsafullyqualifiedclassnameofaJava158JavaServletSpecificationexceptiontype.
Thesub-elementlocationelementcontainsthelocationoftheresourceinthewebapplicationrelativetotherootofthewebapplication.
Thevalueofthelocationmusthavealeading'/'.
FIGURE14-10error-pageElementStructure16.
jsp-configElementThejsp-configisusedtoprovideglobalconfigurationinformationfortheJSPfilesinawebapplication.
Ithastwosub-elements,taglibandjsp-property-group.
ThetaglibelementcanbeusedtoprovideinformationonataglibrarythatisusedbyaJSPpagewithintheWebapplication.
SeeJavaServerPagesspecificationversion2.
1fordetail.
FIGURE14-11jsp-configElementStructureChapter14DeploymentDescriptor15917.
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-constraintindicateshowdatacommunicatedbetweentheclient160JavaServletSpecificationandcontainershouldbeprotectedbythesub-elementtransport-guarantee.
Thelegalvaluesofthetransport-guaranteeiseitheroneofNONE,INTEGRAL,orCONFIDENTIAL.
FIGURE14-12security-constraintElementStructure18.
login-configElementThelogin-configisusedtoconfiguretheauthenticationmethodthatshouldbeused,therealmnamethatshouldbeusedforthisapplication,andtheattributesthatareneededbytheformloginmechanism.
Thesub-elementauth-methodconfigurestheauthenticationmechanismfortheWebapplication.
TheelementcontentmustbeeitherBASIC,DIGEST,FORM,CLIENT-CERT,oraChapter14DeploymentDescriptor161vendor-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-qualifiedJavatypeoftheenvironmententryvaluethatis162JavaServletSpecificationexpectedbytheapplication'scode.
Thesub-elementenv-entry-valuedesignatesthevalueofadeploymentcomponent'senvironmententry.
ThevaluemustbeaStringthatisvalidfortheconstructorofthespecifiedtypethattakesasingleStringasaparameter,orasinglecharacterforjava.
lang.
Character.
Theoptionalinjection-targetelementisusedtodefinetheinjectionofthenamedresourceintofieldsorJavaBeansproperties.
Aninjection-targetspecifiesaclassandanamewithinthatclassintowhicharesourceshouldbeinjected.
Theinjection-target-classspecifiesthefullyqualifiedclassnamethatisthetargetoftheinjection.
Theinjection-target-namespecifiesthetargetwithinthespecifiedclass.
ThetargetisfirstlookedforasaJavaBeanpropertyname.
Ifnotfound,thetargetislookedforasafieldname.
ThespecifiedresourcewillbeinjectedintothetargetduringinitializationoftheclassbyeithercallingthesetmethodforthetargetpropertyorbysettingavalueintothenameChapter14DeploymentDescriptor163filed.
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-linkspecifiesthatanEJBreferenceislinkedtothe164JavaServletSpecificationenterprisebean.
SeeJavaPlatform,EnterpriseEdition,version6formoredetail.
Inadditiontotheseelements,theinjection-targetelementcanbeusedtodefineinjectionofthenamedenterprisebeanintoacomponentfieldorproperty.
FIGURE14-16ejb-refElementStructure22.
ejb-local-refElementChapter14DeploymentDescriptor165Theejb-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-166JavaServletSpecificationqnameelementdeclaresthespecificWSDLserviceelementthatisbeingreferredto.
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-refElementStructureChapter14DeploymentDescriptor16724.
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-refElementStructure168JavaServletSpecification25.
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.
ThenameisaChapter14DeploymentDescriptor169JNDInamerelativetothejava: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.
170JavaServletSpecificationExample:FIGURE14-21message-destination-refElementStructurejms/StockQueuejavax.
jms.
QueueConsumesCorporateStocksChapter14DeploymentDescriptor17127.
message-destinationElementThemessage-destinationspecifiesamessagedestination.
Thelogicaldestinationdescribedbythiselementismappedtoaphysicaldestinationbythedeployer.
Themessage-destination-nameelementspecifiesanameforamessagedestination.
Thisnamemustbeuniqueamongthenamesofmessagedestinationswithinthedeploymentfile.
Example:FIGURE14-22message-destinationElementStructure28.
locale-encoding-mapping-listElementThelocale-encoding-mapping-listcontainsthemappingbetweenthelocaleandtheencoding.
specifiedbythesub-elementlocale-encoding-mapping.
CorporateStocks172JavaServletSpecificationExample:FIGURE14-23locale-encoding-mapping-listElementStructure14.
5ExamplesThefollowingexamplesillustratetheusageofthedefinitionslistedinthedeploymentdescriptorschema.
jaShift_JISChapter14DeploymentDescriptor17314.
5.
1ABasicExampleCODEEXAMPLE14-1BasicDeploymentDescriptorExampleASimpleApplicationWebmasterwebmaster@mycorp.
comcatalogcom.
mycorp.
CatalogServletcatalogSpringcatalog/catalog/*30pdfapplication/pdfindex.
jspindex.
htmlindex.
htm404/404.
html174JavaServletSpecification14.
5.
2AnExampleofSecurityCODEEXAMPLE14-2DeploymentDescriptorExampleUsingSecurityASecureApplicationcatalogcom.
mycorp.
CatalogServletcatalogSpringMGRmanagermanagercatalog/catalog/*SalesInfo/salesinfo/*GETPOSTmanagerCONFIDENTIALChapter14DeploymentDescriptor175CODEEXAMPLE14-2DeploymentDescriptorExampleUsingSecurity176JavaServletSpecification177CHAPTER15RequirementsrelatedtootherSpecificationsThischapterliststherequirementsforwebcontainersthatareincludedinproductsthatalsoincludeotherJavatechnologies.
InthefollowingsectionsanyreferencetoJavaEEappliestonotonlythefullJavaEEprofilebutalsoanyprofilethatincludessupportforServlet,liketheJavaEEWebProfile.
FormoreinformationonprofilespleaserefertotheJavaEEplatformspecification.
15.
1SessionsDistributedservletcontainersthatarepartofaJavaEEimplementationmustsupportthemechanismnecessaryformigratingotherJavaEEobjectsfromoneJVMtoanother.
15.
2WebApplications15.
2.
1WebApplicationClassLoaderServletcontainersthatarepartofaJavaEEproductshouldnotallowtheapplicationtooverrideJavaSEorJavaEEplatformclasses,suchasthoseinjava.
*andjavax.
*namespaces,thateitherJavaSEorJavaEEdonotallowtobemodified.
178JavaServletSpecification15.
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.
Chapter15RequirementsrelatedtootherSpecifications179Thenameofthepre-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.
Thefollowingsectionscallouttherequirements180JavaServletSpecification15.
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=196Chapter15RequirementsrelatedtootherSpecifications18115.
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-RPC182JavaServletSpecificationspecifications,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-69.
Chapter15RequirementsrelatedtootherSpecifications18315.
4.
3RulesforProcessingtheDeploymentDescriptorThecontainersandtoolsthatarepartofJavaEEtechnology-compliantimplementationarerequiredtovalidatethedeploymentdescriptoragainsttheXMLschemaforstructuralcorrectness.
Thevalidationisrecommended,butnotrequiredforthewebcontainersandtoolsthatarenotpartofaJavaEEtechnologycompliantimplementation.
15.
5AnnotationsandResourceInjectionTheJavaMetadataspecification(JSR-175),whichispartofJ2SE5.
0andgreater,providesameansofspecifyingconfigurationdatainJavacode.
MetadatainJavacodeisalsoreferredtoasannotations.
InJavaEE,annotationsareusedtodeclaredependenciesonexternalresourcesandconfigurationdatainJavacodewithouttheneedtodefinethatdatainaconfigurationfile.
ThissectiondescribesthebehaviorofannotationsandresourceinjectioninJavaEEtechnologycompliantServletcontainers.
ThissectionexpandsontheJavaEEspecificationsection5titled"Resources,Naming,andInjection.
"AnnotationsmustbesupportedonthefollowingcontainermanagedclassesthatimplementthefollowinginterfacesandaredeclaredinthewebapplicationdeploymentdescriptororusingtheannotationsdefinedinSection8.
1,"Annotationsandpluggability"onpage8-65oraddedprogrammatically.
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.
AsyncListener184JavaServletSpecificationReferencesmustbeinjectedpriortoanylifecyclemethodsbeingcalledandthecomponentinstancebeingmadeavailabletheapplication.
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.
Chapter15RequirementsrelatedtootherSpecifications185Followingisanexampleofhowthisannotationwouldbeused.
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.
xmlBusinessAdmin186JavaServletSpecificationInthecaseaboveareferencetotheEJBcomponent"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{//.
.
.
}Chapter15RequirementsrelatedtootherSpecifications187Anexampleofa@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;188JavaServletSpecification15.
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(){.
.
.
}Chapter15RequirementsrelatedtootherSpecifications189The@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)})190JavaServletSpecificationIntheexampleaboveaJMSconnectionfactoryandadatasourcearemadeavailabletotheCalculatorServletbymeansofan@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@ResourcesExampleChapter15RequirementsrelatedtootherSpecifications191Theexampleaboveshowshowaservletusesthe@RunAsannotationtopropagatethesecurityidentity"Admin"toanEJBcomponentwhenthemyCart.
getTotal()methodiscalled.
ForfurtherdetailsonpropagatingidentitiesseeSection15.
3.
1,"PropagationofSecurityIdentityinEJBCalls"onpage15-180.
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.
15ManagedBeansandJSR299requirementsInaproductthatalsosupportsManagedBeans,implementationsMUSTsupportuseofManagedBeansasServlets,FiltersandListeners.
InaproductthatalsosupportsJSR299,implementationsMUSTsimilarlysupportuseofJSR299-stylemanagedbeans.
InaproductthatalsosupportsJSR-299,animplementationmustsupportuseof299-stylemanagedbeansasServlet,Filter,Listener,HttpUpgradeHandlerclassesinanapplication.
Servletannotationsmaybedirectlyappliedtothesebeans.
JSR-299specifiestherequirementsforthesecontainer-managedbeaninstanceswithrespecttoinstantiation,injectionandotherservices.
JSR-299defines@Dependentpseudo-scope,Servlets,FiltersandListenersMUSTbeinthatscope.
192JavaServletSpecification193APPENDIXAChangeLogThisdocumentisthefinalreleaseoftheJavaServlet3.
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.
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".
7.
Section5.
1,"Buffering".
AndjavadocofServletResponse.
ClarifiedthebehaviorofServletResponse.
reset.
8.
Section6.
2.
1,"FilterLifecycle"(4).
Requiredfiltersandservletprocessinginthesamethread.
9.
Section7.
2,"CreatingaSession".
Addchangesessionid.
10.
Section8.
1,"Annotationsandpluggability",Section8.
2.
1,"Modularityofweb.
xml"andSection1.
6.
1,"Processingannotations".
Clarifythebehaviorofmetadata-complete.
11.
Section8.
1.
1,"@WebServlet".
Programmaticallyaddingservletwithanamedifferentfromthatspecifiedinannotation.
12.
Section8.
2.
2,"Orderingofweb.
xmlandweb-fragment.
xml"andSection8.
2.
4,"Sharedlibraries/runtimespluggability".
TheprocessingofHandlesTypesannotationisappliedirrespectivetosettingofmetadata-complete.
13.
Section8.
2.
3,"Assemblingthedescriptorfromweb.
xml,web-fragment.
xmlandannotations".
Clarifytheorderinwhichlistenersareinvoked.
14.
Section8.
2.
4,"Sharedlibraries/runtimespluggability"ClarifythecreationofinstanceofServletCotnainerInitilizer.
15.
Section9.
4,"TheForwardMethod".
Clarifiedthebehavioroftheresponsewhentherequestisputinasynchronousmode.
16.
TABLE11-2.
Adda"Changestoid"events.
17.
Section10.
9.
2,"ErrorPages"andSection14.
4,"DeploymentDescriptorDiagram".
Adddescriptionfordefaulterrorpage.
18.
Section11.
3.
3,"ListenerRegistration".
Add"correspondingtogivenevents".
19.
Section12.
2,"SpecificationofMappings".
Clarifythebehaviorofservletsmappedtothesameurl-pattern.
20.
Section15.
3.
1,"PropagationofSecurityIdentityinEJBCalls".
ExplicitlymentionedtheServlet.
initandServlet.
destroy.
21.
Section15.
5.
15,"ManagedBeansandJSR299requirements".
AddHttpUpgradeHandler.
22.
AddedgenericinServletRequestWrapper,ServletResponseWrapperandHandlesTypes.
AppendixAChangeLog19523.
JavadocofHttpServletResponse.
sendRedirect:Supportednetwork-pathreference.
24.
AddnewmethodsServletRequest.
getContentLengthLongandServletResponse.
setContentLengthLong.
A.
2ChangessinceServlet3.
0ProposedFinalDraft1.
Re-factoredsomeoftheAsyncAPIs-movedaddAsyncListenertoAsyncContextandrenamedittoaddListener.
MovedsetAsyncTimeouttoAsyncContextandrenamedittosetTimeout.
2.
Clarifiedsomeofthesemanticsaroundconcurrentaccesstotherequestandresponseinasyncprocessing.
3.
Updatedpluggabilityrulesforresourcereferenceelements.
4.
Addedanewannotation-@ServletSecurity(andassociatedannotationforthefields)fordefiningsecurityasopposedtore-usingthe@RolesAllowed,@PermitAll,@DenyAllA.
3ChangessinceServlet3.
0PublicReview1.
UpdatedisAsyncStartedtoreturnfalseonceadispatchtothecontaineroracalltocompleteisdonefromtheasynchandler2.
Addedorderingsupportforfragments3.
Addedsupportforfileupload4.
AddedsupportforloadingstaticresourcesandJSPsfromJARfilesthatareincludedintheMETA-INF/resourcesdirectoryoftheJARfilewhichisthenbundledintheWEB-INF/libdirectory5.
ChangedannotationnamesbasedonfeedbackonPublicReviewofthespecification6.
Addedprogrammaticlogin/logoutsupport7.
Addedsupportforsecurityrelatedcommonannotations-@RolesAllowed,@PermitAll,@DenyAll196JavaServletSpecification8.
ClarifiedwelcomefilesA.
4ChangessinceServlet3.
0EDR1.
Thesuspend/resumeAPIsarenolongerpresentinthespecification.
TheyhavebeenreplacedbystartAsyncandAsyncContextwhichnowhasforwardandcompletemethods.
2.
Annotationnameshavechangedandthereareonlytoplevelannotations.
Themethodlevelannotationsfordeclaringtheservletmethodsarenolongerbeingused.
3.
Therulesforassemblingweb.
xmlfromfragmentsandannotationsisdescribed.
A.
5ChangessinceServlet2.
5MR61.
Addedsupportforannotationsandwebfragments2.
Addedsupportforsuspend/resumetoallowasyncsupportinservlets.
3.
AddedsupportforinitializingservletsandfiltersfromtheServletContextatinitializationtime.
4.
AddedsupportforHttpOnlycookiesandallowconfiguringcookies.
5.
AddedconveniencemethodstoServletRequesttogetResponseandServletContextA.
6ChangessinceServlet2.
5MR5A.
6.
1ClarifySRV8.
4"TheForwardMethod"Changethelastsentenceofthesectionwhichcurrentlyis:AppendixAChangeLog197"BeforetheforwardmethodoftheRequestDispatcherinterfacereturns,theresponsecontentmustbesentandcommitted,andclosedbytheservletcontainer.
"toread:"BeforetheforwardmethodoftheRequestDispatcherinterfacereturnswithoutexception,theresponsecontentmustbesentandcommitted,andclosedbytheservletcontainer.
IfanerroroccursinthetargetoftheRequestDispatcher.
forward()theexceptionmaybepropogatedbackthroughallthecallingfiltersandservletsandeventuallybacktothecontainer.
"A.
6.
2UpdateDeploymentdescriptor"http-methodvaluesallowed"Thefacetforhttp-methodelementinthedeploymentdescriptoriscurrentlymorerestrictivethanthehttpspecification.
Thefollowingchangeisbeingmadetothedescriptortoallowthesetofmethodnamesasdefinedbythehttpspecification.
Thepatternvalueofhttp-methodTypeisbeingchangedfromtocloselymatchwhattheHTTPspecificationlistsasallowableHTTPmethodsnames.
A.
6.
3ClarifySRV7.
7.
1"ThreadingIssues"Changetheparagraphwhichcurrentlyis:"Multipleservletsexecutingrequestthreadsmayhaveactiveaccesstoasinglesessionobjectatthesametime.
TheDeveloperhastheresponsibilityforsynchronizingaccesstosessionresourcesasappropriate.
"toread:"Multipleservletsexecutingrequestthreadsmayhaveactiveaccesstothesamesessionobjectatthesametime.
Thecontainermustensurethatmanipulationofinternaldatastructuresrepresentingthesessionattributesisperformedinathreadsafemanner.
TheDeveloperhastheresponsibilityforthreadsafeaccesstotheattributeobjectsthemselves.
ThiswillprotecttheattributecollectioninsidetheHttpSessionobjectfromconcurrentaccess,eliminatingtheopportunityforanapplicationtocausethatcollectiontobecomecorrupted.
"198JavaServletSpecificationA.
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:IfthisrequesthasbeenforwardedusingRequestDispatcher.
forward(ServletRequest,ServletResponse),theserverpathinthereconstructedURLmustreflectthepathusedtoobtaintheRequestDispatcher,andnottheserverpathspecifiedbytheclient.
BecausethismethodreturnsaStringBuffer,notastring,youcanmodifytheURLeasily,forexample,toappendqueryparameters.
A.
7.
4RemovalofIllegalStateExceptionfromHttpSession.
getId()TheHttpSessionBindingListenercallsthevalueUnboundeventafterthesessionhasbeenexpired,unfortunately,theHttpSession.
getId()methodisoftenusedinthisscenarioandissupposedtothrowanIllegalStateException.
TheservletEGagreedtoremovetheexceptionfromtheAPItopreventthesetypesofexceptions.
AppendixAChangeLog199A.
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.
InsuchcasesthismethodwillreturntheactualcontextpathusedbytherequestanditmaydifferfromthepathreturnedbytheServletContext.
getContextPath()method.
ThecontextpathreturnedbyServletContext.
getContextPath()shouldbeconsideredastheprimeorpreferredcontextpathoftheapplication.
A.
7.
6Requirementforweb.
xmlinwebapplicationsSection10.
13,"Inclusionofaweb.
xmlDeploymentDescriptor"wasaddedwhichremovesrequirementforJavaEEcompliantwebapplications.
Thesectionisasfollows:AwebapplicationisNOTrequiredtocontainaweb.
xmlifitdoesNOTcontainanyServlet,Filter,orListenercomponents.
InotherwordsanapplicationcontainingonlystaticfilesorJSPpagesdoesnotrequireaweb.
xmltobepresent.
200JavaServletSpecificationA.
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.
"A.
8.
2FilterAllDispatchesModifiedSection6.
2.
5,"FiltersandtheRequestDispatcher"toclarifyawaytomapafiltertoallservletdispatchesbyappendingthefollowingtexttotheendofthesection:Finally,thefollowingcodeusesthespecialservletname'*':CODEEXAMPLEA-1Exampleofspecialservletname'*'AllDispatchFilter*FORWARDAppendixAChangeLog201ThiscodewouldresultintheAllDispatchFilterbeinginvokedonrequestdispatcherforward()callsforallrequestdispatchersobtainedbynameorbypath.
A.
8.
3MultipleOccurrencesofServletMappingsPreviousversionsoftheservletschemaallowsonlyasingleurl-patternorservletnameperservletmapping.
ForservletsmappedtomultipleURLsthisresultsinneedlessrepetitionofwholemappingclauses.
Thedeploymentdescriptorservlet-mappingTypewasupdatedto:A.
8.
4MultipleOccurrencesFilterMappingsPreviousversionsoftheservletschemaallowsonlyasingleurl-patterninafiltermapping.
ForfiltersmappedtomultipleURLsthisresultsinneedlessrepetitionofwholemappingclauses.
Thedeploymentdescriptorschemathefilter-mappingTypewasupdatedto:CODEEXAMPLEA-2servlet-mappingTypedescriptorCODEEXAMPLEA-3Updatedfilter-mappingTypeschema202JavaServletSpecificationThischangeallowsmultiplepatternsandservletnamestobedefinedinasinglemappingascanbeseeninthefollowingexample:Section6.
2.
4,"ConfigurationofFiltersinaWebApplication"wasupdatedtoclarifythecaseswheretherearemultiplemappingswiththefollowingtext:"Ifafiltermappingcontainsbothand,thecontainermustexpandthefiltermappingintomultiplefiltermappings(oneforeachand),preservingtheorderoftheandelements.
"Anexampleswasalsoprovidedtoclarifycaseswhentherearemultiplemappings.
A.
8.
5SupportAlternativeHTTPMethodswithAuthorizationConstraintsThepreviousServlet2.
4schemarestrictedHTTPmethodstoGET,POST,PUT,DELETE,HEAD,OPTIONS,andTRACE.
Theschemahttp-methodTypewaschangedfrom:CODEEXAMPLEA-4FiltermappingexampleDemoFilter/foo/*/bar/*LoggerREQUESTERRORCODEEXAMPLEA-5Servlet2.
4http-methodTypeschema.
.
.
CODEEXAMPLEA-3Updatedfilter-mappingTypeschemaAppendixAChangeLog203Tothefollowing:Thehttp-methodelementsnowneedtobeatokenasdescribedinHTTP1.
1specificationsection2.
2.
A.
8.
6MinimumJ2SERequirementServlet2.
5ContainersnowrequireJ2SE5.
0astheminimumJavaversion.
Section1.
2,"WhatisaServletContainer"wasupdatedtoreflectthisrequirement.
A.
8.
7AnnotationsandResourceInjectionJavaEEtechnologycompliantcontainersrequireannotationsandresourceinjectiononservlets,filters,andlisteners.
Section15.
5,"AnnotationsandResourceInjection"describestheannotationsandresourceinjectioninfurtherdetail.
CODEEXAMPLEA-6Servlet2.
5http-methodTypeschemaAHTTPmethodtypeasdefinedinHTTP1.
1section2.
2.
CODEEXAMPLEA-5Servlet2.
4http-methodTypeschema204JavaServletSpecificationA.
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.
Section5.
6,"ClosureofResponseObject"wasupdatedtoallowallheaderstobesetbychanging:"TheamountofcontentspecifiedinthesetContentLengthmethodoftheresponseandhasbeenwrittentotheresponse"Tothefollowing:"TheamountofcontentspecifiedinthesetContentLengthmethodoftheresponsehasbeengreaterthanzeroandhasbeenwrittentotheresponse"AppendixAChangeLog205A.
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)Clarificationthatthesecuritymodelisalsoappliedtofilter(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)206JavaServletSpecificationAddHttpSessionActivationListenerandHttpSessionBindingListenerintotheTable10-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)Addthedescriptionaboutthecasewhenthecontainerhasacachingmechanism(1.
2)ValidatingdeploymentdescriptoragainsttheschemaisrequiredforJavaEEcontainers(13.
2)Subelementsundercanbeinanarbitraryorder(13.
2)Oneexampleofthecontainer'srejectingthewebapplicationwasremovedduetothecontradictionwithSRV.
11.
1(9.
5)url-patternTypeischangedfromj2ee:stringtoxsd:string(13)Thesub-elementsunderindeploymentdescriptorcanbeinthearbitraryorder(13)AppendixAChangeLog207Thecontainermustinformadeveloperwithadescriptiveerrormessagewhendeploymentdescriptorfilecontainsanillegalcharacterormultipleelementsof,,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)AddmissinggetParameterMap()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)208JavaServletSpecificationRequiredclassloaderextensionmechanism(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-209GlossaryAApplicationDeveloperTheproducerofawebapplication.
TheoutputofanApplicationDeveloperisasetofservletclasses,JSPpages,HTMLpages,andsupportinglibrariesandfiles(suchasimages,compressedarchivefiles,etc.
)forthewebapplication.
TheApplicationDeveloperistypicallyanapplicationdomainexpert.
Thedeveloperisrequiredtobeawareoftheservletenvironmentanditsconsequenceswhenprogramming,includingconcurrencyconsiderations,andcreatethewebapplicationaccordingly.
ApplicationAssemblerTakestheoutputoftheApplicationDeveloperandensuresthatitisadeployableunit.
Thus,theinputoftheApplicationAssembleristheservletclasses,JSPpages,HTMLpages,andothersupportinglibrariesandfilesforthewebapplication.
TheoutputoftheApplicationAssemblerisawebapplicationarchiveorawebapplicationinanopendirectorystructure.
DDeployerTheDeployertakesoneormorewebapplicationarchivefilesorotherdirectorystructuresprovidedbyanApplicationDeveloperanddeploystheapplicationintoaspecificoperationalenvironment.
TheoperationalenvironmentincludesGlossary-210JavaServletSpecificationaspecificservletcontainerandwebserver.
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-211ServletContainerProviderAvendorthatprovidestheruntimeenvironment,namelytheservletcontainerandpossiblythewebserver,inwhichawebapplicationrunsaswellasthetoolsnecessarytodeploywebapplications.
TheexpertiseoftheContainerProviderisinHTTP-levelprogramming.
Sincethisspecificationdoesnotspecifytheinterfacebetweenthewebserverandtheservletcontainer,itislefttotheContainerProvidertosplittheimplementationoftherequiredfunctionalitybetweenthecontainerandtheserver.
servletdefinitionAuniquenameassociatedwithafullyqualifiedclassnameofaclassimplementingtheServletinterface.
Asetofinitializationparameterscanbeassociatedwithaservletdefinition.
servletmappingAservletdefinitionthatisassociatedbyaservletcontainerwithaURLpathpattern.
Allrequeststothatpathpatternarehandledbytheservletassociatedwiththeservletdefinition.
SystemAdministratorThepersonresponsiblefortheconfigurationandadministrationoftheservletcontainerandwebserver.
Theadministratorisalsoresponsibleforoverseeingthewell-beingofthedeployedwebapplicationsatruntime.
Thisspecificationdoesnotdefinethecontractsforsystemmanagementandadministration.
TheadministratortypicallyusesruntimemonitoringandmanagementtoolsprovidedbytheContainerProviderandservervendorstoaccomplishthesetasks.
Glossary-212JavaServletSpecificationUuniformresourcelocator(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-213webapplicationarchiveAsinglefilethatcontainsallofthecomponentsofawebapplication.
ThisarchivefileiscreatedbyusingstandardJARtoolswhichallowanyorallofthewebcomponentstobesigned.
Webapplicationarchivefilesareidentifiedbythe.
warextension.
Anewextensionisusedinsteadof.
jarbecausethatextensionisreservedforfileswhichcontainasetofclassfilesandthatcanbeplacedintheclasspathordoubleclickedusingaGUItolaunchanapplication.
Asthecontentsofawebapplicationarchivearenotsuitableforsuchuse,anewextensionwasinorder.
webapplication,distributableAwebapplicationthatiswrittensothatitcanbedeployedinawebcontainerdistributedacrossmultipleJavavirtualmachinesrunningonthesamehostordifferenthosts.
Thedeploymentdescriptorforsuchanapplicationusesthedistributableelement.
Glossary-214JavaServletSpecification

白丝云-美国圣何塞4837/德国4837大带宽/美西9929,26元/月起

官方网站:点击访问白丝云官网活动方案:一、KVM虚拟化套餐A1核心 512MB内存 10G SSD硬盘 800G流量 2560Mbps带宽159.99一年 26一月套餐B1核心 512MB内存 10G SSD硬盘 2000G流量 2560Mbps带宽299.99一年 52一月套餐...

95IDC香港特价物理机服务器月付299元起,5个ip/BGP+CN2线路;美国CERA服务器仅499元/月起

95idc是一家香港公司,主要产品香港GIA线路沙田CN2线路独服,美国CERA高防服务器,日本CN2直连服务器,即日起,购买香港/日本云主机,在今年3月份,95IDC推出来一款香港物理机/香港多ip站群服务器,BGP+CN2线路终身7折,月付350元起。不过今天,推荐一个价格更美的香港物理机,5个ip,BGP+CN2线路,月付299元起,有需要的,可以关注一下。95idc优惠码:优惠码:596J...

木木云35元/月,美国vps服务器优惠,1核1G/500M带宽/1T硬盘/4T流量

木木云怎么样?木木云品牌成立于18年,此为贵州木木云科技有限公司旗下新运营高端的服务器的平台,目前已上线美国中部大盘鸡,母鸡采用E5-267X系列,硬盘全部组成阵列。目前,木木云美国vps进行了优惠促销,1核1G/500M带宽/1T硬盘/4T流量,仅35元/月。点击进入:木木云官方网站地址木木云优惠码:提供了一个您专用的优惠码: yuntue目前我们有如下产品套餐:DV型 1H 1G 500M带宽...

pathinfo为你推荐
朗科ios5三星itunesDescriptionios5iphonewifi苹果wifi版和4G版是什么意思,有什么区别吗csshack针对IE6的CSS HACK是什么?google统计google分析里的数据包括搜索引擎爬虫的数据吗?Google中文专题交流苹果5.1.1越狱你好,iphone5.1.1完美越狱,电脑上为什么连不上呢?只能显示充电,谢谢chrome18怎么关闭chrome的自动更新,稳定版要18了,mactype要悲剧了ios7好用吗IOS7系统好不好Flash开启自动运行指引
购买域名和空间 awardspace 国外空间 韩国网名大全 双线主机 网络空间租赁 重庆双线服务器托管 万网主机管理 如何登陆阿里云邮箱 带宽测试 国外代理服务器 北京主机托管 免费主页空间 新疆服务器 godaddy退款 游戏服务器 在线tracert 达拉斯 cc攻击 neobux 更多