The Java EE 6 Tutorial Volume II

The Java EE 6 Tutorial Volume II

-

Documents
732 pages
Lire
Le téléchargement nécessite un accès à la bibliothèque YouScribe
Tout savoir sur nos offres

Description

TheJavaEE6Tutorial,VolumeII
AdvancedTopics
SunMicrosystems,Inc.
4150NetworkCircle
SantaClara,CA95054
U.S.A.
PartNo:820–7628–10
December2009 Copyright2009SunMicrosystems,Inc. 4150NetworkCircle,SantaClara,CA95054U.S.A. Allrightsreserved.
SunMicrosystems,Inc.hasintellectualpropertyrightsrelatingtotechnologyembodiedintheproductthatisdescribedinthisdocument.Inparticular,andwithout
limitation,theseintellectualpropertyrightsmayincludeoneormoreU.S.patentsorpendingpatentapplicationsintheU.S.andinothercountries.
U.S.GovernmentRights–Commercialsoftware.GovernmentusersaresubjecttotheSunMicrosystems,Inc.standardlicenseagreementandapplicableprovisions
oftheFARanditssupplements.
Thisdistributionmayincludematerialsdevelopedbythirdparties.
PartsoftheproductmaybederivedfromBerkeleyBSDsystems,licensedfromtheUniversityofCalifornia.UNIXisaregisteredtrademarkintheU.S.andother
countries,exclusivelylicensedthroughX/OpenCompany,Ltd.
Sun,SunMicrosystems,theSunlogo,theSolarislogo,theJavaCoffeeCuplogo,docs.sun.com,EnterpriseJavaBeans,EJB,GlassFish,J2EE,J2SE,JavaNamingand
DirectoryInterface,JavaBeans,Javadoc,JDBC,JDK,JavaScript,JavaServer,JavaServerPages,JMX,JRE,JSP,JVM,MySQL,NetBeans,OpenSolaris,SunSolve,Sun
GlassFish,Java,andSolarisaretrademarksorregisteredtrademarksofSunMicrosystems,Inc.oritssubsidiariesintheU.S.andothercountries.AllSPARC
trademarksareusedunderlicenseandaretrademarksorregisteredtrademarksofSPARCInternational,Inc.intheU.S ...

Sujets

Informations

Publié par
Nombre de visites sur la page 325
Langue English
Signaler un problème
TheJavaEE6Tutorial,VolumeII AdvancedTopics SunMicrosystems,Inc. 4150NetworkCircle SantaClara,CA95054 U.S.A. PartNo:820–7628–10 December2009 Copyright2009SunMicrosystems,Inc. 4150NetworkCircle,SantaClara,CA95054U.S.A. Allrightsreserved. SunMicrosystems,Inc.hasintellectualpropertyrightsrelatingtotechnologyembodiedintheproductthatisdescribedinthisdocument.Inparticular,andwithout limitation,theseintellectualpropertyrightsmayincludeoneormoreU.S.patentsorpendingpatentapplicationsintheU.S.andinothercountries. U.S.GovernmentRights–Commercialsoftware.GovernmentusersaresubjecttotheSunMicrosystems,Inc.standardlicenseagreementandapplicableprovisions oftheFARanditssupplements. Thisdistributionmayincludematerialsdevelopedbythirdparties. PartsoftheproductmaybederivedfromBerkeleyBSDsystems,licensedfromtheUniversityofCalifornia.UNIXisaregisteredtrademarkintheU.S.andother countries,exclusivelylicensedthroughX/OpenCompany,Ltd. Sun,SunMicrosystems,theSunlogo,theSolarislogo,theJavaCoffeeCuplogo,docs.sun.com,EnterpriseJavaBeans,EJB,GlassFish,J2EE,J2SE,JavaNamingand DirectoryInterface,JavaBeans,Javadoc,JDBC,JDK,JavaScript,JavaServer,JavaServerPages,JMX,JRE,JSP,JVM,MySQL,NetBeans,OpenSolaris,SunSolve,Sun GlassFish,Java,andSolarisaretrademarksorregisteredtrademarksofSunMicrosystems,Inc.oritssubsidiariesintheU.S.andothercountries.AllSPARC trademarksareusedunderlicenseandaretrademarksorregisteredtrademarksofSPARCInternational,Inc.intheU.S.andotherProductsbearing SPARCtrademarksarebaseduponanarchitecturedevelopedbySunMicrosystems,Inc. TMTheOPENLOOKandSun GraphicalUserInterfacewasdevelopedbySunMicrosystems,Inc.foritsusersandlicensees.Sunacknowledgesthepioneeringefforts ofXeroxinresearchinganddevelopingtheconceptofvisualorgraphicaluserinterfacesforthecomputerindustry.Sunholdsanon-exclusivelicensefromXeroxto theXeroxGraphicalUserInterface,whichlicensealsocoversSun'slicenseeswhoimplementOPENLOOKGUIsandotherwisecomplywithSun'swrittenlicense agreements. ProductscoveredbyandinformationcontainedinthispublicationarecontrolledbyU.S.ExportControllawsandmaybesubjecttotheexportorimportlawsin othercountries.Nuclear,missile,chemicalorbiologicalweaponsornuclearmaritimeendusesorendusers,whetherdirectorindirect,arestrictlyprohibited.Export orreexporttocountriessubjecttoU.S.embargoortoentitiesidentifiedonU.S.exportexclusionlists,including,butnotlimitedto,thedeniedpersonsandspecially designatednationalslistsisstrictlyprohibited. DOCUMENTATIONISPROVIDED“ASIS”ANDALLEXPRESSORIMPLIEDCONDITIONS,REPRESENTATIONSANDWARRANTIES,INCLUDINGANY IMPLIEDWARRANTYOFMERCHANTABILITY,FITNESSFORAPARTICULARPURPOSEORNON-INFRINGEMENT,AREDISCLAIMED,EXCEPTTO THEEXTENTTHATSUCHDISCLAIMERSAREHELDTOBELEGALLYINVALID. Copyright2009SunMicrosystems,Inc. 4150NetworkCircle,SantaClara,CA95054U.S.A. Tousdroitsréservés. SunMicrosystems,Inc.détientlesdroitsdepropriétéintellectuellerelatifsàlatechnologieincorporéedansleproduitquiestdécritdanscedocument.Enparticulier, etcesanslimitation,cesdroitsdepropriétéintellectuellepeuventinclureunouplusieursbrevetsaméricainsoudesapplicationsdebrevetenattenteauxEtats-Unis etdansd'autrespays. Cettedistributionpeutcomprendredescomposantsdéveloppéspardestiercespersonnes. CertainescomposantsdeceproduitpeuventêtredérivéesdulogicielBerkeleyBSD,licenciésparl'UniversitédeCalifornie.UNIXestunemarquedéposéeaux Etats-Unisetdansd'autrespays;elleestlicenciéeexclusivementparX/OpenCompany,Ltd. Sun,SunMicrosystems,lelogoSun,lelogoSolaris,lelogoJavaCoffeeCup,docs.sun.com,EnterpriseJavaBeans,EJB,GlassFish,J2EE,J2SE,JavaNamingand DirectoryInterface,JavaBeans,Javadoc,JDBC,JDK,JavaScript,JavaServer,JavaServerPages,JMX,JRE,JSP,JVM,MySQL,NetBeans,OpenSolaris,SunSolve,Sun GlassFish,JavaetSolarissontdesmarquesdefabriqueoudesmarquesdéposéesdeSunMicrosystems,Inc.,ousesfiliales,auxEtats-Unisetdansd'autrespays. TouteslesmarquesSPARCsontutiliséessouslicenceetsontdesdefabriqueoudesmarquesdéposéesdeSPARCInternational,Inc.auxEtats-Unisetdans d'autrespays.LesproduitsportantlesmarquesSPARCsontbaséssurunearchitecturedéveloppéeparSunMicrosystems,Inc. L'interfaced'utilisationgraphiqueOPENLOOKetSunaétédéveloppéeparSunMicrosystems,Inc.poursesutilisateursetlicenciés.Sunreconnaîtleseffortsde pionniersdeXeroxpourlarechercheetledéveloppementduconceptdesinterfacesd'utilisationvisuelleougraphiquepourl'industriedel'informatique.Sundétient unelicencenonexclusivedeXeroxsurl'interfaced'utilisationgraphiqueXerox,cettelicencecouvrantégalementleslicenciésdeSunquimettentenplacel'interface d'utilisationgraphiqueOPENLOOKetqui,enoutre,seconformentauxlicencesécritesdeSun. Lesproduitsquifontl'objetdecettepublicationetlesinformationsqu'ilcontientsontrégisparlalegislationaméricaineenmatièredecontrôledesexportationset peuventêtresoumisaudroitd'autrespaysdansledomainedesexportationsetimportations.Lesutilisationsfinales,ouutilisateursfinaux,pourdesarmesnucléaires, desmissiles,desarmeschimiquesoubiologiquesoupourlenucléairemaritime,directementouindirectement,sontstrictementinterdites.Lesexportationsou réexportationsversdespayssousembargodesEtats-Unis,ouversdesentitésfigurantsurleslistesd'exclusiond'exportationaméricaines,ycompris,maisdemanière nonexclusive,lalistedepersonnesquifontobjetd'unordredenepasparticiper,d'unefaçondirecteouindirecte,auxexportationsdesproduitsoudesservicesqui sontrégisparlalegislationaméricaineenmatièredecontrôledesexportationsetlalistederessortissantsspécifiquementdesignés,sontrigoureusementinterdites. LADOCUMENTATIONESTFOURNIE"ENL'ETAT"ETTOUTESAUTRESCONDITIONS,DECLARATIONSETGARANTIESEXPRESSESOUTACITES SONTFORMELLEMENTEXCLUES,DANSLAMESUREAUTORISEEPARLALOIAPPLICABLE,YCOMPRISNOTAMMENTTOUTEGARANTIE IMPLICITERELATIVEALAQUALITEMARCHANDE,AL'APTITUDEAUNEUTILISATIONPARTICULIEREOUAL'ABSENCEDECONTREFACON. 091210@23031 Contents Preface...................................................................................................................................................23 PartI Introduction..........31 1 Overview................33 JavaEE6Highlights ............................................................................................................................34 JavaEEApplicationModel .................................................................................................................34 DistributedMultitieredApplications ...............................................................................................35 Security..........................................................................................................................................36 JavaEEComponents ...................................................................................................................37 JavaEEClients..............................................................................................................................37 WebComponents......39 BusinessC .................................................................................................................40 EnterpriseInformationSystemTier..........................................................................................41 JavaEEContainers...............41 ContainerServices .......................................................................................................................42 CTypes...........................................................................................................................42 WebServicesSupport............44 XML ...............................................................................................................................................44 SOAPTransportProtocol ...........................................................................................................45 WSDLStandardFormat..............................................................................................................45 JavaEEApplicationAssemblyandDeployment .............................................................................45 PackagingApplications............46 DevelopmentRoles .............................................................................................................................47 JavaEEProductProvider..48 ToolProvider................................................................................................................................48 ApplicationComponentProvider .............................................................................................48 3 Contents ApplicationAssembler ................................................................................................................49 ADeployerandAdministrator.................................................................................49 JavaEE6APIs ......................................................................................................................................50 EnterpriseJavaBeansTechnology..............................................................................................50 JavaServletTechnology ..............................................................................................................50 JavaServerFacesTechnology......................................................................................................51 JPages .....................................................................................................51 JavaServerPagesStandardTagLibrary .....................................................................................51 JavaPersistenceAPI.....................................................................................................................52 JavaTransactionAPI......52 JavaAPIforRESTfulWebServices(JAX-RS) ..........................................................................52 JavaMessageServiceAPI..52 JavaEEConnectorArchitecture ................................................................................................53 JavaMailAPI .................................................................................................................................53 JavaAuthorizationServiceProviderContractforContainers(JavaACC) ..........................53 JavaAuthenticationServiceProviderInterfaceforC(JASPIC) ............................53 JavaAPIforXMLRegistries .......................................................................................................54 SimplifiedSystemsIntegration...................................................................................................54 JavaEE6APIsIncludedintheJavaPlatform,StandardEdition6.0(JavaSE6)..........................55 JavaDatabaseConnectivityAPI.................................................................................................55 JavaNamingandDirectoryInterface ........................................................................................55 JavaBeansActivationFramework ..............................................................................................56 JavaAPIforXMLProcessing .....................................................................................................56 JavaArchitectureforXMLBinding(JAXB) .............................................................................56 SOAPwithAttachmentsAPIforJava56 JavaAPIforXMLWebServices(JAX-WS) ..............................................................................57 JavaAuthenticationandAuthorizationService .......................................................................57 SunGlassFishEnterpriseServerv3 ...................................................................................................57 Tools ..............................................................................................................................................57 2 UsingtheTutorialExamples ..............................................................................................................59 RequiredSoftware ...............................................................................................................................59 JavaPlatform,StandardEdition59 JavaEE6SoftwareDevelopmentKit(SDK) .............................................................................60 ApacheAnt ...................................................................................................................................60 4 TheJavaEE6Tutorial,VolumeII • December2009 Contents JavaEE6TutorialComponent...................................................................................................61 NetBeansIDE ...............................................................................................................................62 StartingandStoppingtheEnterpriseServer ....................................................................................63theAdministrationConsole ................................................................................................64 ▼ToStarttheAConsoleinNetBeansIDE ..........................................................64 StartingandStoppingtheJavaDBDatabaseServer........................................................................64 BuildingtheExamples ........................................................................................................................65 TutorialExampleDirectoryStructure ..............................................................................................65 GettingtheLatestUpdatestotheTutorial .......................................................................................66 ▼ToUpdatetheTutorialthroughtheUpdateCenter................................................................66 DebuggingJavaEEApplications .......................................................................................................66 UsingtheServerLog ....................................................................................................................66 UsingaDebugger.........................................................................................................................67 PartII TheWebTier .........................................................................................................................................69 3 GettingStartedwithWebApplications...........................................................................................71 WebApplications ................................................................................................................................71 WebApplicationLifeCycle................................................................................................................73 WebModules .......................................................................................................................................75 PackagingWebModules .............................................................................................................76 DeployingaWARFile .................................................................................................................77 TestingDeployedWebModules ................................................................................................79 ListingDeployedWebModules .................................................................................................79 UpdatingWebModules ..............................................................................................................79 UndeployingWebModules80 ConfiguringWebApplications..........................................................................................................81 MappingURLstoWebComponents ........................................................................................81 DeclaringWelcomeFiles ............................................................................................................83 SettingInitializationParameters83 MappingErrorstoErrorScreens ...............................................................................................85 DeclaringResourceReferences ..................................................................................................86 FurtherInformationaboutWebApplications.................................................................................88 5 Contents 4 JavaServerFacesTechnology ............................................................................................................89 WhatIsaJavaServerFacesApplication?...........................................................................................90 JavaServerFacesTechnologyBenefits ..............................................................................................91 CreatingaSimpleJavaServerFacesApplication..............................................................................92 DevelopingBackingBeans .........................................................................................................92 CreatingtheWebPage ................................................................................................................93 MappingtheFacesServletInstance94 TheLifecycleofthehelloWorldApplication ...........................................................................94 ▼RunningtheApplicationinNetBeansIDE...............................................................................95 FurtherInformationaboutJavaServerFacesTechnology..............................................................96 5 IntroductiontoFacelets .....................................................................................................................97 AdvantagesofFacelets ........................................................................................................................97 What'sFacelets? ..................................................................................................................................98 WebPages .....................................................................................................................................98 TagLibrarySupport.....................................................................................................................98 UnifiedExpressionLanguageSupport......................................................................................99 DevelopingaSimpleFaceletsApplication .......................................................................................99 CreatingaFaceletsApplication ................................................................................................100 ConfiguringtheA.....................................................................................................103 Building,Packaging,DeployingandRunningtheApplication ...........................................105 Templating .........................................................................................................................................107 CompositeComponents ..................................................................................................................109 Resources............................................................................................................................................112 6 UnifiedExpressionLanguage..........................................................................................................113 OverviewofEL...................................................................................................................................113 ImmediateandDeferredEvaluationSyntax...........................................................................114 ValueandMethodExpressions................................................................................................116 DefiningaTagAttributeType..................................................................................................122 LiteralExpressions.....................................................................................................................123 Operators..............124 ReservedWords .........................................................................................................................125 ExamplesofELExpressions .....................................................................................................125 6 TheJavaEE6Tutorial,VolumeII • December2009 Contents 7 UsingJavaServerFacesTechnologyinWebPages ......................................................................127 SettingUpaPage ...............................................................................................................................127 AddingComponentstoaPageUsingHTMLTags .......................................................................128 CommonComponentTagAttributes .....................................................................................131 AddingHTMLHeadandBodyTags .......................................................................................133 AddingaFormComponent .....................................................................................................133 UsingTextComponents ...........................................................................................................134 UsingCommandComponentsforPerformingActionsandNavigation ...........................139 AddingGraphicsandImagesWiththeh:graphicImageTag .............................................141 LayingOutComponentsWiththePanelComponent.........................................................141 DisplayingCforSelectingOneValue .................................................................143 RenderingComponentsforMultipleValues145 UsingTheSelectItemandSelectItemsComponents.......................................................147 UsingData-BoundTableComponents ..................................................................................148 DisplayingErrorMessagesWiththeh:messageandh:messagesTags .............................152 CreatingBookmarkableURLswithh:buttonandh:linkTags .........................................153 ResourceRelocationusingh:outputTags .............................................................................154 UsingCoreTags ................................................................................................................................157 8 UsingConverters,ListenersandValidators ..................................................................................159 UsingtheStandardConverters........................................................................................................159 ConvertingaComponent’sValue............................................................................................160 UsingDateTimeConverter .......................................................................................................161 UsingNumberConverter ...........................................................................................................163 RegisteringListenersonComponents164 RegisteringaValue-ChangeListeneronaComponent ........................................................165anActionListeneronaComponent ...................................................................166 UsingtheStandardValidators....166 ValidatingaComponent’sValue .............................................................................................167 UsingtheLongRangeValidator ..............................................................................................167 ReferencingaBackingBeanMethod168aMethodThatPerformsNavigation .................................................................169 ReferencingaMethodThatHandlesanActionEvent ..........................................................169aMethodThatPerformsValidation ..................................................................169 ReferencingaMethodThatHandlesaValue-ChangeEvent ...............................................170 7 Contents 9 DevelopingWithJavaServerFacesTechnology ...........................................................................171 BackingBeans ....................................................................................................................................171 CreatingaBackingBean ...........................................................................................................171 WritingBeanProperties ...................................................................................................................174 WritingPBoundtoComponentValues .................................................................175PropertiesBoundtoCInstances.............................................................181 WritingPBoundtoConverters,Listeners,orValidators .....................................182 WritingBackingBeanMethods ......................................................................................................183 WritingaMethodtoHandleNavigation ................................................................................183aMethodtoHandleanActionEvent ........................................................................185 WritingaMethodtoPerformValidation ...............................................................................185aMethodtoHandleaValue-ChangeEvent.............................................................186 BeanValidation .................................................................................................................................187 10 ConfiguringJavaServerFacesApplications..................................................................................189 ApplicationConfigurationResourceFile .......................................................................................189 OrderingofApplicationConfigurationResources ...............................................................190 ConfiguringProjectStage.................................................................................................................192 CBeans.............................................................................................................................192 Usingthemanaged-beanElement............................................................................................193 InitializingPropertiesUsingthemanaged-propertyElement ............................................195 IMapsandLists ........................................................................................................201 UsingAnnotations.....................................................................................................................201 RegisteringCustomErrorMessagesasaResourceBundle ..........................................................202CustomLocalizedStaticText ......................................................................................203 DefaultValidator........203 ConfiguringNavigationRules .........................................................................................................204 ImplicitNRules .........................................................................................................207 BasicRequirementsofaJavaServerFacesApplication .................................................................207 ConfiguringanApplicationWithaDeploymentDescriptor...............................................208 IncludingtheClasses,Pages,andOtherResources ...............................................................212 11 JavaServletTechnology ...................................................................................................................213 WhatIsaServlet?...............................................................................................................................213 ServletLifeCycle................................................................................................................................214 8 TheJavaEE6Tutorial,VolumeII • December2009 Contents HandlingServletLife-CycleEvents .........................................................................................214 HServletErrors.............................................................................................................215 SharingInformation .........................................................................................................................216 UsingScopeObjects ..................................................................................................................216 ControllingConcurrentAccesstoSharedResources ...........................................................216 InitializingaServlet ...........................................................................................................................217 WritingServiceMethods........217 GettingInformationfromRequests ........................................................................................218 ConstructingResponses............................................................................................................219 FilteringRequestsandResponses....................................................................................................220 ProgrammingFilters.....220 PCustomizedRequestsandResponses ............................................................221 SpecifyingFilterMappings .......................................................................................................222 InvokingOtherWebResources.......................................................................................................224 IncludingOtherintheResponse ...........................................................................225 TransferringControltoAnotherWebComponent..............................................................225 AccessingtheWebContext..............................................................................................................226 MaintainingClientState..........226 AccessingaSession ....................................................................................................................226 AssociatingObjectswithaSession ..........................................................................................226 SessionManagement...227 SessionTracking ........................................................................................................................227 FinalizingaServlet.............................................................................................................................228 TrackingServiceRequests ........................................................................................................228 NotifyingMethodstoShutDown ............................................................................................229 CreatingPoliteLong-RunningMethods.................................................................................230 FurtherInformationaboutJavaServletTechnology ....................................................................230 PartIII WebServices ......................................................................................................................................231 12 IntroductiontoWebServices ..........................................................................................................233 WhatAreWebServices?...................................................................................................................233 TypesofWebServices.......................................................................................................................233 DecidingWhichTypeofWebServicetoUse ................................................................................236 WhenShouldIUseJAX-WS?...................................................................................................236 9 Contents WhenShouldIUseJAX-RS? ....................................................................................................236 13 BuildingWebServiceswithJAX-WS ...............................................................................................237 SettingthePort...................................................................................................................................238 CreatingaSimpleWebServiceandClientwithJAX-WS ............................................................238 RequirementsofaJAX-WSEndpoint .....................................................................................239 CodingtheServiceEndpointImplementationClass240 Building,Packaging,andDeployingtheService ....................................................................240 TestingtheServicewithoutaClient ........................................................................................242 ASimpleJAX-WSClient...........................................................................................................242 TypesSupportedbyJAX-WS ...........................................................................................................244 WebServicesInteroperabilityandJAX-WS ..................................................................................245 FurtherInformationaboutJAX-WS ...............................................................................................245 14 BuildingRESTfulWebServiceswithJAX-RSandJersey .............................................................247 WhatareWebServices? ....................................................................................................247 WhereDoesJerseyFitIn?248 CreatingaRESTfulRootResourceClass........................................................................................248 DevelopingRESTfulWebServiceswithJAX-RSandJersey.................................................249 OverviewofaJersey-AnnotatedApplication .........................................................................250 The@PathAnnotationandURIPathTemplates ..................................................................251 RespondingtoHTTPResources ..............................................................................................254 Using@Consumesand@ProducestoCustomizeRequestsandResponses ......................257 ExtractingRequestParameters ................................................................................................259 OverviewofJAX-RSandJersey:FurtherInformation ..........................................................262 ExampleApplicationsforJAX-RSandJersey ................................................................................263 CreatingaRESTfulWebService263 Example:CreatingaSimpleHelloWorldApplicationUsingJAX-RSandJersey .............270AddingontotheSimpleHelloWorldRESTfulWebService ..............................273 JAX-RSintheFirstCupExample ............................................................................................275 RealWorldExamples ................................................................................................................275 FurtherInformation..........................................................................................................................275 10 TheJavaEE6Tutorial,VolumeII • December2009