jersey 2.3
TRANSCRIPT
-
Links:TableofContents|SingleHTML
Jersey2.3.1UserGuide
TableofContents
Preface1.GettingStarted
1.1.CreatingaNewProjectfromMavenArchetype1.2.ExploringtheNewlyCreatedProject1.3.RunningtheProject1.4.CreatingaJavaEEWebApplication1.5.ExploringOtherJerseyExamples
2.Modulesanddependencies2.1.JavaSECompatibility2.2.IntroductiontoJerseydependencies2.3.CommonJerseyUseCases
2.3.1.ServletbasedapplicationonGlassfish2.3.2.Servletbasedserversideapplication2.3.3.ClientapplicationonJDK2.3.4.Serversideapplicationonsupportedcontainers
2.4.Listofmodules3.JAXRSApplication,ResourcesandSubResources
[email protected].@GET,@PUT,@POST,@DELETE,...(HTTPMethods)[email protected].@Consumes
3.2.ParameterAnnotations(@*Param)3.3.Subresources3.4.LifecycleofRootResourceClasses3.5.RulesofInjection3.6.Useof@Context3.7.Programmaticresourcemodel
4.DeployingaRESTfulWebService4.1.AutoDiscoverableFeatures
4.1.1.ConfiguringtheFeatureAutodiscoverymechanism4.2.Turnoffclasspathscanning
5.ClientAPI5.1.UniformInterfaceConstraint5.2.EaseofuseandreusingJAXRSartifacts5.3.OverviewoftheClientAPI
5.3.1.GettingstartedwiththeclientAPI5.3.2.CreatingandconfiguringaClientinstance5.3.3.Targetingawebresource5.3.4.IdentifyingresourceonWebTarget5.3.5.InvokingaHTTPrequest5.3.6.Examplesummary
5.4.Javainstancesandtypesforrepresentations5.4.1.Addingsupportfornewrepresentations
5.5.ClientTransportConnectors5.6.Usingclientrequestandresponsefilters5.7.Closingconnections5.8.SecuringaClient
5.8.1.HTTPBasicAuthenticationSupport5.8.2.HTTPDigestAuthenticationSupport
6.RepresentationsandResponses6.1.RepresentationsandJavaTypes6.2.BuildingResponses6.3.WebApplicationExceptionandMappingExceptionstoResponses6.4.ConditionalGETsandReturning304(NotModified)Responses
7.JAXRSEntityProviders7.1.Introduction7.2.HowtoWriteCustomEntityProviders
7.2.1.MessageBodyWriter7.2.2.MessageBodyReader
7.3.EntityProviderSelection7.4.JerseyMessageBodyWorkersAPI7.5.DefaultJerseyEntityProviders
8.SupportforCommonMediaTypeRepresentations8.1.JSON
8.1.1.ApproachestoJSONSupport8.1.2.MOXy8.1.3.JavaAPIforJSONProcessing(JSONP)8.1.4.Jackson8.1.5.Jettison8.1.6.@JSONPJSONwithPaddingSupport
8.2.XML8.2.1.LowlevelXMLsupport8.2.2.GettingstartedwithJAXB8.2.3.POJOs8.2.4.UsingcustomJAXBContext8.2.5.MOXy
8.3.Multipart8.3.1.Overview8.3.2.Client8.3.3.Server
9.FiltersandInterceptors
-
9.1.Introduction9.2.Filters
9.2.1.Serverfilters9.2.2.Clientfillers
9.3.Interceptors9.4.Filterandinterceptorexecutionorder9.5.Namebinding9.6.Dynamicbinding9.7.Priorities
10.AsynchronousServicesandClients10.1.AsynchronousServerAPI
10.1.1.AsynchronousServersideCallbacks10.1.2.ChunkedOutput
10.2.ClientAPI10.2.1.AsynchronousClientCallbacks10.2.2.Chunkedinput
11.URIsandLinks11.1.BuildingURIs11.2.ResolveandRelativize11.3.Link
12.ProgrammaticAPIforBuildingResources12.1.Introduction12.2.ProgrammaticHelloWorldexample
12.2.1.Deploymentofprogrammaticresources12.3.Additionalexamples12.4.Modelprocessors
13.ServerSentEvents(SSE)Support13.1.WhatareServerSentEvents13.2.WhentouseServerSentEvents13.3.JerseyServerSentEventsAPI13.4.ImplementingSSEsupportinaJAXRSresource
13.4.1.SimpleSSEresourcemethod13.4.2.BroadcastingwithJerseySSE
13.5.ConsumingSSEeventswithJerseyclients13.5.1.ReadingSSEeventswithEventInput13.5.2.AsynchronousSSEprocessingwithEventSource
14.Security14.1.Securingserver
14.1.1.SecurityContext14.1.2.Authorizationsecuringresources
14.2.ClientSecurity14.3.OAuth
15.WADLSupport15.1.WADLintroduction15.2.Configuration15.3.ExtendedWADLsupport
16.BeanValidationSupport16.1.BeanValidationDependencies16.2.EnablingBeanValidationinJersey16.3.ConfiguringBeanValidationSupport16.4.ValidatingJAXRSresourcesandmethods
16.4.1.ConstraintAnnotations16.4.2.AnnotationconstraintsandValidators16.4.3.EntityValidation16.4.4.AnnotationInheritance
16.7.1.ValidationError16.8.Example
17.EntityDataFiltering17.1.EnablingandconfiguringEntityFilteringinyourapplication17.2.ComponentsusedtodescribeEntityFilteringconcepts17.3.Usingcustomannotationstofilterentities
17.3.1.ServersideEntityFiltering17.3.2.ClientsideEntityFiltering
17.4.RolebasedEntityFilteringusing(javax.annotation.security)annotations17.5.Definingcustomhandlingforentityfilteringannotations17.6.SupportingEntityDataFilteringincustomentityprovidersorframeworks17.7.ModuleswithsupportforEntityDataFiltering17.8.Examples
18.MVCTemplates18.1.Dependencies18.2.RegistrationandConfiguration18.3.Explicitvs.ImplicitViewTemplates
18.3.1.ViewableExplicitViewTemplates18.3.2.@TemplateImplicitViewTemplates
18.4.JSP18.5.CustomTemplatingEngines18.6.OtherExamples
19.Monitoringanddiagnostics19.1.Introduction19.2.EventListeners
19.2.1.GuidelinesforimplementingJerseyeventlisteners19.2.2.MonitoringStatistics19.2.3.MonitoringStatisticsasMBeans
20.SpringDI20.1.Dependencies20.2.RegistrationandConfiguration
-
20.3.Example21.JerseyTestFramework
21.1.Basics21.2.SupportedContainers21.3.Advancedfeatures
21.3.1.JerseyTestFeatures21.3.2.Externalcontainer21.3.3.TestClientconfiguration21.3.4.Accessingtheloggedtestrecordsprogrammatically
22.BuildingandTestingJersey22.1.CheckingOuttheSource22.2.BuildingtheSource22.3.Testing22.4.UsingNetBeans
23.MigrationGuide23.1.MigratingfromJersey2.0,2.1or2.2to2.323.2.MigratingfromJersey1.xto2.0
23.2.1.ServerAPI23.2.2.MigratingJerseyClientAPI
A.ConfigurationPropertiesA.1.Common(client/server)configurationpropertiesA.2.ServerconfigurationpropertiesA.3.Clientconfigurationproperties
ListofTables
2.1.JerseyCore2.2.JerseyContainers2.3.JerseyConnectors2.4.JerseyMedia2.5.JerseyExtensions2.6.JerseyTestFramework2.7.JerseyGlassfishBundles2.8.JerseyExamples2.9.JerseyExamplesWebApps3.1.Resourcescopes3.2.Overviewofinjectiontypes8.1.DefaultpropertyvaluesforMOXyMessageBodyReader/MessageBodyWriter23.1.MappingofJersey1.xtoJAXRS2.0clientclassesA.1.ListofcommonconfigurationpropertiesA.2.ListofserverconfigurationpropertiesA.3.Listofclientconfigurationproperties
ListofExamples
3.1.Simplehelloworldrootresourceclass3.2.SpecifyingURIpathparameter3.3.PUTmethod3.4.SpecifyingoutputMIMEtype3.5.UsingmultipleoutputMIMEtypes3.6.Serversidecontentnegotiation3.7.SpecifyinginputMIMEtype3.8.Queryparameters3.9.CustomJavatypeforconsumingrequestparameters3.10.ProcessingPOSTedHTMLform3.11.ObtaininggeneralmapofURIpathand/orqueryparameters3.12.Obtaininggeneralmapofheaderparameters3.13.Obtaininggeneralmapofformparameters3.14.Exampleofthebeanwhichwillbeusedas@BeanParam3.15.InjectionofMyBeanParamasamethodparameter:3.16.Injectionofmorebeansintooneresourcemethods:3.17.Subresourcemethods3.18.Subresourcelocators3.19.Subresourcelocatorswithemptypath3.20.Subresourcelocatorsreturningsubtype3.21.Subresourcelocatorscreatedfromclasses3.22.Subresourcelocatorsreturningresourcemodel3.23.Injection3.24.Wronginjectionintoasingletonscope3.25.Injectionofproxiesintosingleton3.26.Exampleofpossibleinjections4.1.Deploymentagnosticapplicationmodel4.2.ReusingJerseyimplementationinyourcustomapplicationmodel4.3.DeploymentofaJAXRSapplicationusing@ApplicationPathwithServlet3.04.4.Configurationofmavenwarplugininpom.xmlwithServlet3.04.5.DeploymentofaJAXRSapplicationusingweb.xmlwithServlet3.04.6.DeploymentofyourapplicationusingJerseyspecificservlet4.7.UsingJerseyspecificservletwithoutanapplicationmodelinstance4.8.RegisteringSPIimplementationsusingResourceConfig5.1.POSTrequestwithformparameters5.2.UsingJAXRSClientAPI5.3.UsingJAXRSClientAPIfluently5.4.Closingconnections6.1.UsingFilewithaspecificmediatypetoproducearesponse6.2.Returning201statuscodeandaddingLocationheaderinresponsetoPOSTrequest6.3.Addinganentitybodytoacustomresponse6.4.Throwingexceptionstocontrolresponse6.5.Applicationspecificexceptionimplementation6.6.Mappinggenericexceptionstoresponses6.7.ConditionalGETsupport7.1.Exampleresourceclass7.2.MyBeanentityclass7.3.MessageBodyWriterexample7.4.Exampleofassignmentofannotationstoaresponseentity7.5.ClientcodetestingMyBeanMessageBodyWriter7.6.ResultofMyBeanMessageBodyWritertest7.7.MessageBodyReaderexample
-
7.8.TestingMyBeanMessageBodyReader7.9.ResultoftestingMyBeanMessageBodyReader7.10.MessageBodyReaderregisteredonaJAXRSclient7.11.Resultofclientcodeexecution7.12.UsageofMessageBodyWorkersinterface8.1.SimpleJAXBbeanimplementation8.2.JAXBbeanusedtogenerateJSONrepresentation8.3.TweakingJSONformatusingJAXB8.4.JAXBbeancreation8.5.ConstructingaJsonObject(JSONProcessing)8.6.ConstructingaJSONObject(Jettison)8.7.MoxyJsonConfigSettingproperties.8.8.ContextResolver8.9.SettingpropertiesforMOXyprovidersintoConfigurable8.10.BuildingclientwithMOXyJSONfeatureenabled.8.11.CreatingJAXRSapplicationwithMOXyJSONfeatureenabled.8.12.BuildingclientwithJSONProcessingJSONfeatureenabled.8.13.CreatingJAXRSapplicationwithJSONProcessingJSONfeatureenabled.8.14.ContextResolver8.15.BuildingclientwithJacksonJSONfeatureenabled.8.16.CreatingJAXRSapplicationwithJacksonJSONfeatureenabled.8.17.JAXBbeansforJSONsupportednotationsdescription,simpleaddressbean8.18.JAXBbeansforJSONsupportednotationsdescription,contactbean8.19.JAXBbeansforJSONsupportednotationsdescription,initialization8.20.XMLnamespacetoJSONmappingconfigurationforJettisonbasedmappednotation8.21.JSONexpressionwithXMLnamespacesmappedintoJSON8.22.JSONArrayconfigurationforJettisonbasedmappednotation8.23.JSONexpressionwithJSONarraysexplicitlyconfiguredviaJersey8.24.JSONexpressionproducedusingbadgerfishnotation8.25.ContextResolver8.26.BuildingclientwithJettisonJSONfeatureenabled.8.27.CreatingJAXRSapplicationwithJettisonJSONfeatureenabled.8.28.Simplestcaseofusing@[email protected]@JSONPwithconfiguredparameters.8.31.LowlevelXMLtestmethodsaddedtoHelloWorldResource.java8.32.Planetclass8.33.Resourceclass8.34.MethodforconsumingPlanet8.35.ResourceclassJAXBElement8.36.ClientsideJAXBElement8.37.PlanetJAXBContextProvider8.38.UsingProviderwithJAXRSclient8.39.Addjerseymediamoxydependency.8.40.RegistertheMoxyXmlFeatureclass.8.41.ConfigureandregisteranMoxyXmlFeatureinstance.8.42.BuildingclientwithMultiPartfeatureenabled.8.43.CreatingJAXRSapplicationwithMultiPartfeatureenabled.8.44.MultiPartentity8.45.MultiPartentityinHTTPmessage.8.46.FormDataMultiPartentity8.47.FormDataMultiPartentityinHTTPmessage.8.48.Multipartsendingfiles.8.49.ResourcemethodusingMultiPartasinputparameter/returnvalue.8.50.Useof@FormDataParamannotation9.1.Containerresponsefilter9.2.Containerrequestfilter9.3.Prematchingrequestfilter9.4.Clientrequestfilter9.5.GZIPwriterinterceptor9.6.GZIPreaderinterceptor9.7.@NameBindingexample9.8.Dynamicbindingexample9.9.Prioritiesexample10.1.Simpleasyncresource10.2.Simpleasyncmethodwithtimeout10.3.CompletionCallbackexample10.4.ChunkedOutputexample10.5.Simpleclientasyncinvocation10.6.Simpleclientfluentasyncinvocation10.7.Clientasynccallback10.8.Clientasynccallbackforspecificentity10.9.ChunkedInputexample11.1.URIbuilding11.2.BuildingURIsusingqueryparameters12.1.Astandardresourceclass12.2.Aprogrammaticresource12.3.Aprogrammaticresource12.4.Aprogrammaticresource12.5.Aprogrammaticresource12.6.Aprogrammaticresource13.1.SimpleSSEresourcemethod13.2.BroadcastingSSEmessages13.3.RegisteringEventListenerwithEventSource13.4.OverridingEventSource.onEvent(InboundEvent)method14.1.AccessingSecurityContext14.2.InjectingSecurityContextintoasingletonresource14.3.Securingresourcesusingweb.xml14.4.RegisteringRolesAllowedDynamicFeatureusingResourceConfig14.5.InjectingSecurityContextintosingletons15.1.AsimpleWADLexampleJAXRSresourcedefinition15.2.AsimpleWADLexampleWADLcontent15.3.OPTIONSmethodreturningWADL15.4.MorecomplexWADLexampleJAXRSresourcedefinition15.5.MorecomplexWADLexampleWADLcontent16.1.ConfiguringJerseyspecificpropertiesforBeanValidation.16.2.UsingValidationConfigtoconfigureValidator.16.3.Constraintannotationsoninputparameters
-
16.4.Constraintannotationsonfields16.5.Constraintannotationsonclass16.6.Definitionofaconstraintannotation16.7.Validatorimplementation.16.8.Entityvalidation16.9.Entityvalidation216.10.Responseentityvalidation16.11.Validategetteronexecution16.12.InjectingUriInfointoaConstraintValidator16.13.SupportforinjectingJersey'sresources/providersviaConstraintValidatorFactory.16.14.ValidationErrortotext/plain16.15.ValidationErrortotext/html16.16.ValidationErrortoapplication/xml16.17.ValidationErrortoapplication/json17.1.Registeringandconfiguringentityfilteringfeatureonserver.17.2.Registeringandconfiguringentityfilteringfeaturewithsecurityannotationsonserver.17.3.Registeringandconfiguringentityfilteringfeatureonclient.17.4.Project17.5.User17.6.Task17.7.ProjectsResource17.8.ProjectDetailedView17.9.AnnotatedProject17.10.AnnotatedUser17.11.AnnotatedTask17.12.ProjectsResourceResponseentityfilteringannotations17.13.ProjectsResourceEntityfilteringannotationsonmethods17.14.ClientRequestentityfilteringannotations17.15.ClientRequestentityfilteringannotations17.16.Entityfilteringannotationwithcustommeaning17.17.EntityDataFilteringsupportinMOXyJSONbindingprovider18.1.RegisteringMvcFeature18.2.RegisteringJspMvcFeature18.3.SettingMvcProperties.TEMPLATE_BASE_PATHvalueinResourceConfig18.4.SettingFreemarkerMvcProperties.TEMPLATE_BASE_PATHvalueinweb.xml18.5.UsingViewableinaresourceclass18.6.UsingabsolutepathtotemplateinViewable18.7.Using@Templateonaresourceclass18.8.CustomTemplateProcessor18.9.RegisteringcustomTemplateProcessor19.1.Applicationeventlistener19.2.Requesteventlistener19.3.Eventlistenertestresource19.4.InjectingMonitoringStatistics23.1.Jersey1reloaderimplementation23.2.Jersey1reloaderregistration23.3.Jersey2reloaderimplementation23.4.Jersey2reloaderregistration
Preface
ThisisuserguideforJersey2.3.1.Wearetryingtokeepituptodateasweaddnewfeatures.Whenreadingtheuserguide,pleaseconsultalsoourJerseyAPIdocumentationasanadditionalsourceofinformationaboutJerseyfeaturesandAPI.
Ifyouwouldliketocontributetotheguideorhavequestionsonthingsnotcoveredinourdocs,[email protected],incaseyouspotanyerrorsintheJerseydocumentation,pleasereportthembyfilinganewissueinourJerseyJIRAIssueTrackerunderdocscomponent.PleasemakesuretospecifytheversionoftheJerseyUserGuidewheretheerrorhasbeenspottedbyselectingthepropervaluefortheAffectedVersionfield.
TextformattingconventionsFirstmentionofanyJerseyandJAXRSAPIcomponentinasectionlinkstotheAPIdocumentationofthereferencedcomponent.Anysubsequentmentionsofthecomponentinthesamechapterarerenderedusingamonospacefont.
Emphasisedfontisusedtoacallattentiontoanewlyintroduceconcept,whenitfirstoccursinthetext.
Insomeofthecodelistings,certainlinesaretoolongtobedisplayedononelinefortheavailablepagewidth.Insuchcase,thelinesthatexceedtheavailablepagewidtharebrokenupintomultiplelinesusinga'\'attheendofeachlinetoindicatethatabreakhasbeenintroducedtofitthelineinthepage.Forexample:
Thisisanoverlylonglinethat\mightnotfittheavailablepage\widthandhadtobebrokeninto\multiplelines.
Thislinefitsthepagewidth.
Shouldreadas:
Thisisanoverlylonglinethatmightnotfittheavailablepagewidthandhadtobebrokenintomultiplelines.
Thislinefitsthepagewidth.
Chapter1.GettingStarted
TableofContents
1.1.CreatingaNewProjectfromMavenArchetype1.2.ExploringtheNewlyCreatedProject1.3.RunningtheProject1.4.CreatingaJavaEEWebApplication1.5.ExploringOtherJerseyExamples
ThischapterprovidesaquickintroductiononhowtogetstartedbuildingRESTfulservicesusingJersey.TheexampledescribedhereusesthelightweightGrizzlyHTTPserver.AttheendofthischapteryouwillseehowtoimplementequivalentfunctionalityasaJavaEEwebapplicationyoucandeployonanyservletcontainersupportingServlet2.5andhigher.
-
1.1.CreatingaNewProjectfromMavenArchetypeJerseyprojectisbuildusingApacheMavensoftwareprojectbuildandmanagementtool.AllmodulesproducedaspartofJerseyprojectbuildarepushedtotheCentralMavenRepository.ThereforeitisveryconvenienttoworkwithJerseyforanyMavenbasedprojectasallthereleased(nonSNAPSHOT)JerseydependenciesarereadilyavailablewithoutaneedtoconfigureaspecialmavenrepositorytoconsumetheJerseymodules.
Note
IncaseyouwanttodependonthelatestSNAPSHOTversionsofJerseymodules,thefollowingrepositoryconfigurationneedstobeaddedtoyourMavenprojectpom:
SincestartingfromaMavenprojectisthemostconvenientwayforworkingwithJersey,let'snowhavealookatthisapproach.WewillnowcreateanewJerseyprojectthatrunsontopofaGrizzlycontainer.WewilluseaJerseyprovidedmavenarchetype.Tocreatetheproject,executethefollowingMavencommandinthedirectorywherethenewprojectshouldreside:
FeelfreetoadjustthegroupId,packageand/orartifactIdofyournewproject.Alternatively,youcanchangeitbyupdatingthenewprojectpom.xmlonceitgetsgenerated.
1.2.ExploringtheNewlyCreatedProject
OncetheprojectgenerationfromaJerseymavenarchetypeissuccessfullyfinished,youshouldseethenewsimpleserviceprojectdirectorycreatedinyourcurrentlocation.ThedirectorycontainsastandardMavenprojectstructure:
Projectbuildandmanagementconfigurationisdescribedinthepom.xmllocatedintheprojectrootdirectory.Projectsourcesarelocatedundersrc/main/java.Projecttestsourcesarelocatedundersrc/test/java.
Thereare2classesintheprojectsourcedirectoryinthecom.examplepackage.TheMainclassisresponsibleforbootstrappingtheGrizzlycontaineraswellasconfiguringanddeployingtheproject'sJAXRSapplicationtothecontainer.AnotherclassinthesamepackageisMyResourceclass,thatcontainsimplementationofasimpleJAXRSresource.Itlookslikethis:
AJAXRSresourceisanannotatedPOJOthatprovidessocalledresourcemethodsthatareabletohandleHTTPrequestsforURIpathsthattheresourceisboundto.SeeChapter3,JAXRSApplication,ResourcesandSubResourcesforacompleteguidetoJAXRSresources.Inourcase,theresourceexposesasingleresourcemethodthatisabletohandleHTTPGETrequests,isboundto/myresourceURIpathandcanproduceresponseswithresponsemessagecontentrepresentedin"text/plain"mediatype.Inthisversion,theresourcereturnsthesame"Gotit!"responsetoallclientrequests.
ThelastpieceofcodethathasbeengeneratedinthisskeletonprojectisaMyResourceTestunittestclassthatislocatedinthesamecom.examplepackageastheMyResourceclass,however,thisunittestclassisplacedintothemavenprojecttestsourcedirectorysrc/test/java(certaincodecommentsandJUnitimportshavebeenexcludedforbrevity):
snapshotrepository.java.netJava.netSnapshotRepositoryforMavenhttps://maven.java.net/content/repositories/snapshots/default
mvnarchetype:generateDarchetypeArtifactId=jerseyquickstartgrizzly2\DarchetypeGroupId=org.glassfish.jersey.archetypesDinteractiveMode=false\DgroupId=com.exampleDartifactId=simpleserviceDpackage=com.example\DarchetypeVersion=2.3.1
123456789
10111213141516171819202122232425
packagecom.exampleimportjavax.ws.rs.GETimportjavax.ws.rs.Pathimportjavax.ws.rs.Producesimportjavax.ws.rs.core.MediaType/***Rootresource(exposedat"myresource"path)*/@Path("myresource")publicclassMyResource{/***MethodhandlingHTTPGETrequests.Thereturnedobjectwillbesent*totheclientas"text/plain"mediatype.**@returnStringthatwillbereturnedasatext/plainresponse.*/@GET@Produces(MediaType.TEXT_PLAIN)publicStringgetIt(){return"Gotit!"}}
123456789
10111213141516171819202122232425262728
packagecom.exampleimportjavax.ws.rs.client.Clientimportjavax.ws.rs.client.ClientBuilderimportjavax.ws.rs.client.WebTargetimportorg.glassfish.grizzly.http.server.HttpServer...publicclassMyResourceTest{privateHttpServerserverprivateWebTargettarget@BeforepublicvoidsetUp()throwsException{server=Main.startServer()Clientc=ClientBuilder.newClient()target=c.target(Main.BASE_URI)}@AfterpublicvoidtearDown()throwsException{server.stop()}
-
Inthisunittest,aGrizzlycontainerisfirststartedandserverapplicationisdeployedinthetestsetUp()methodbyastaticcalltoMain.startServer().Next,aJAXRSclientcomponentsarecreatedinthesametestsetupmethod.FirstanewJAXRSclientinstancecisbuiltandthenaJAXRSwebtargetcomponentpointingtothecontextrootofourapplicationdeployedathttp://localhost:8080/myapp/(avalueofMain.BASE_URIconstant)isstoredintoatargetfieldoftheunittestclass.Thisfieldisthenusedintheactualunittestmethod(testGetIt()).
InthetestGetIt()methodafluentJAXRSClientAPIisusedtoconnecttoandsendaHTTPGETrequesttotheMyResourceJAXRSresourceclasslisteningon/myresourceURI.AspartofthesamefluentJAXRSAPImethodinvocationchain,aresponseisreadasaJavaStringtype.Onthesecondlineinthetestmethod,theresponsecontentstringreturnedfromtheserveriscomparedwiththeexpectedphraseinthetestassertion.TolearnmoreaboutusingJAXRSClientAPI,pleaseseetheChapter5,ClientAPIchapter.
1.3.RunningtheProjectNowthatwehaveseenthecontentoftheproject,let'strytotestrunit.Todothis,weneedtoinvokefollowingcommandonthecommandline:
Thiswillcompiletheprojectandruntheprojectunittests.Weshouldseeasimilaroutputthatinformsaboutasuccessfulbuildoncethebuildisfinished:
Results:
Testsrun:1,Failures:0,Errors:0,Skipped:0
[INFO][INFO]BUILDSUCCESS[INFO][INFO]Totaltime:34.527s[INFO]Finishedat:SunMay2619:26:24CEST2013[INFO]FinalMemory:17M/490M[INFO]
Nowthatwehaveverifiedthattheprojectcompilesandthattheunittestpasses,wecanexecutetheapplicationinastandalonemode.Todothis,runthefollowingmavencommand:
Theapplicationstartsandyoushouldsoonseethefollowingnotificationinyourconsole:
May26,20138:08:45PMorg.glassfish.grizzly.http.server.NetworkListenerstartINFO:Startedlistenerboundto[localhost:8080]May26,20138:08:45PMorg.glassfish.grizzly.http.server.HttpServerstartINFO:[HttpServer]Started.JerseyappstartedwithWADLavailableathttp://localhost:8080/myapp/application.wadlHitentertostopit...
Thisinformsyouthattheapplicationhasbeenstartedandit'sWADLdescriptorisavailableathttp://localhost:8080/myapp/application.wadlURL.YoucanretrievetheWADLcontentbyexecutingacurlhttp://localhost:8080/myapp/application.wadlcommandinyourconsoleorbytypingtheWADLURLintoyourfavoritebrowser.YoushouldgetbackanXMLdocumentindescribingyourdeployedRESTfulapplicationinaWADLformat.TolearnmoreaboutworkingwithWADL,checktheChapter15,WADLSupportchapter.
Thelastthingweshouldtrybeforeconcludingthissectionistoseeifwecancommunicatewithourresourcedeployedat/myresourcepath.WecanagaineithertypetheresourceURLinthebrowserorwecanusecurl:
$curlhttp://localhost:8080/myapp/myresourceGotit!
Aswecansee,thecurlcommandreturnedwiththeGotit!messagethatwassentbyourresource.Wecanalsoaskcurltoprovidemoreinformationabouttheresponse,forexamplewecanletitdisplayallresponseheadersbyusingtheiswitch:
curlihttp://localhost:8080/myapp/myresourceHTTP/1.1200OKContentType:text/plainDate:Sun,26May201318:27:19GMTContentLength:7
Gotit!
HereweseethewholecontentoftheresponsemessagethatourJersey/JAXRSapplicationreturned,includingalltheHTTPheaders.NoticetheContentType:text/plainheaderthatwasderivedfromthevalueof@ProducesannotationattachedtotheMyResourceclass.
IncaseyouwanttoseeevenmoredetailsaboutthecommunicationbetweenourcurlclientandourresourcerunningonJerseyinaGrizzlyI/Ocontainer,feelfreetotryothervariousoptionsandswitchesthatcurlprovides.Forexample,thislastcommandwillmakecurloutputalotofadditionalinformationaboutthewholecommunication:
$curlvhttp://localhost:8080/myapp/myresource*Abouttoconnect()tolocalhostport8080(#0)*Trying::1...*Connectionrefused*Trying127.0.0.1...*connected*Connectedtolocalhost(127.0.0.1)port8080(#0)>GET/myapp/myresourceHTTP/1.1>UserAgent:curl/7.25.0(x86_64appledarwin11.3.0)libcurl/7.25.0OpenSSL/1.0.1ezlib/1.2.7libidn/1.22>Host:localhost:8080>Accept:*/*>
-
Gotit!*Closingconnection#0
1.4.CreatingaJavaEEWebApplication
TocreateaWebApplicationthatcanbepackagedasWARanddeployedinaServletcontainerfollowasimilarprocesstotheonedescribedinSection1.1,CreatingaNewProjectfromMavenArchetype.InadditiontotheGrizzlybasedarchetype,JerseyprovidesalsoaMavenarcehtypeforcreatingwebapplicationskeletons.Tocreatethenewwebapplicationskeletonproject,executethefollowingMavencommandinthedirectorywherethenewprojectshouldreside:
AswiththeGrizzlybasedproject,feelfreetoadjustthegroupId,packageand/orartifactIdofyournewwebapplicationproject.Alternatively,youcanchangeitbyupdatingthenewprojectpom.xmlonceitgetsgenerated.
OncetheprojectgenerationfromaJerseymavenarchetypeissuccessfullyfinished,youshouldseethenewsimpleservicewebappprojectdirectorycreatedinyourcurrentlocation.ThedirectorycontainsastandardMavenprojectstructure,similartothesimpleserviceprojectcontentwehaveseenearlier,exceptitisextendedwithanadditionalwebapplicationspecificcontent:
Projectbuildandmanagementconfigurationisdescribedinthepom.xmllocatedintheprojectrootdirectory.Projectsourcesarelocatedundersrc/main/java.Projectresourcesarelocatedundersrc/main/resources.
Projectwebapplicationfilesarelocatedundersrc/main/webapp.
TheprojectcontainsthesameMyResouceJAXRSresourceclass.ItdoesnotcontainanyunittestsaswellasitdoesnotcontainaMainclassthatwasusedtosetupGrizzlycontainerinthepreviousproject.Instead,itcontainsthestandardJavaEEwebapplicationweb.xmldeploymentdescriptorundersrc/main/webapp/WEBINF.Thelastcomponentintheprojectisanindex.jsppagethatservesasaclientfortheMyResourceresourceclassthatispackagedanddeployedwiththeapplication.
TocompileandpackagetheapplicationintoaWAR,invokethefollowingmavencommandinyourconsole:
Asuccessfullbuildoutputwillproduceanoutputsimilartotheonebelow:
Results:
Testsrun:0,Failures:0,Errors:0,Skipped:0
[INFO][INFO]mavenwarplugin:2.1.1:war(defaultwar)@simpleservicewebapp[INFO]Packagingwebapp[INFO]Assemblingwebapp[simpleservicewebapp]in[.../simpleservicewebapp/target/simpleservicewebapp][INFO]Processingwarproject[INFO]Copyingwebappresources[.../simpleservicewebapp/src/main/webapp][INFO]Webappassembledin[75msecs][INFO]Buildingwar:.../simpleservicewebapp/target/simpleservicewebapp.war[INFO]WEBINF/web.xmlalreadyadded,skipping[INFO][INFO]BUILDSUCCESS[INFO][INFO]Totaltime:9.067s[INFO]Finishedat:SunMay2621:07:44CEST2013[INFO]FinalMemory:17M/490M[INFO]
NowyouarereadytotakethepackagedWAR(locatedunder./target/simpleservicewebapp.war)anddeployittoaServletcontainerofyourchoice.
Important
TodeployaJerseyapplication,youwillneedaServletcontainerthatsupportsServlet2.5orlater.Forfullsetofadvancedfeatures(suchasJAXRS2.0AsyncSupport)youwillneedaServlet3.0orlatercompliantcontainer.
1.5.ExploringOtherJerseyExamplesInthesectionsabove,wehavecoveredanapproachhowtogetdirtywithJerseyquickly.PleaseconsulttheothersectionsoftheJerseyUserGuidetolearnmoreaboutJerseyandJAXRS.EventhoughwetryourbesttocoverasmuchaspossiblyintheUserGuide,thereisalwaysachancethatyouwouldnotbeabletogetafullanswertotheproblemyouaresolving.Inthatcase,considerdivinginourexamplesthatprovideadditionaltipsandhintstothefeaturesyoumaywanttouseinyourprojects.
JerseycodebasecontainsanumberofusefulexamplesonhowtousevariousJAXRSandJerseyfeatures.FeelfreetobrowsethroughthecodeofindividualJerseyExamplesintheJerseysourcerepository.Forofflinebrowsing,youcanalsodownloadabundlewithalltheexamplesfromhere.
Chapter2.ModulesanddependenciesTableofContents
2.1.JavaSECompatibility2.2.IntroductiontoJerseydependencies2.3.CommonJerseyUseCases
2.3.1.ServletbasedapplicationonGlassfish2.3.2.Servletbasedserversideapplication2.3.3.ClientapplicationonJDK2.3.4.Serversideapplicationonsupportedcontainers
2.4.Listofmodules
2.1.JavaSECompatibilityAllJerseycomponentsarecompiledwithJavaSE6target.Itmeans,youwillalsoneedatleastJavaSE6tobeabletocompileandrunyourapplication.
2.2.IntroductiontoJerseydependenciesJerseyisbuilt,assembledandinstalledusingApacheMaven.NonsnapshotJerseyreleasesaredeployedtotheCentralMavenRepository.JerseyisalsobeingdeployedtoJava.NetMavenrepositories,whichcontainalsoJerseySNAPSHOTversions.Incaseyouwouldwanttotestthelatestdevelopmentbuilds
mvnarchetype:generateDarchetypeArtifactId=jerseyquickstartwebapp\DarchetypeGroupId=org.glassfish.jersey.archetypesDinteractiveMode=false\DgroupId=com.exampleDartifactId=simpleservicewebappDpackage=com.example\DarchetypeVersion=2.3.1
mvncleanpackage
-
checkouttheJava.NetSnapshotsMavenrepository.
AnapplicationthatusesJerseyanddependsonJerseymodulesisinturnrequiredtoalsoincludeintheapplicationdependenciesthesetof3rdpartymodulesthatJerseymodulesdependon.JerseyisdesignedasapluggablecomponentarchitectureanddifferentapplicationscanthereforerequiredifferentsetsofJerseymodules.ThisalsomeansthatthesetofexternalJerseydependenciesrequiredtobeincludedintheapplicationdependenciesmayvaryineachapplicationbasedontheJerseymodulesthatarebeingusedbytheapplication.
DevelopersusingMavenoraMavenawarebuildsystemintheirprojectsarelikelytofinditeasiertoincludeandmanagedependenciesoftheirapplicationscomparedtodevelopersusingantorotherbuildsystemsthatarenotcompatiblewithMaven.ThisdocumentwillexplaintobothmavenandnonmavendevelopershowtodependonJerseymodulesintheirapplication.AntdevelopersarelikelytofindtheAntTasksforMavenveryuseful.
2.3.CommonJerseyUseCases
2.3.1.ServletbasedapplicationonGlassfish
IfyouareusingGlassfishapplicationserver,youdon'tneedtopackageanythingwithyourapplication,everythingisalreadyincluded.Youjustneedtodeclare(provided)dependencyonJAXRSAPItobeabletocompileyourapplication.
IfyouareusinganyJerseyspecificfeature,youwillneedtodependonJerseydirectly.
2.3.2.Servletbasedserversideapplication
Followingdependenciesapplytoapplicationserver(servletcontainers)withoutanyintegratedJAXRSimplementation.ThenapplicationneedstoincludeJAXRSAPIandJerseyimplementationindeployedapplication.
2.3.3.ClientapplicationonJDK
ApplicationsrunningonplainJDKusingonlyclientpartofJAXRSspecificationneedtodependonlyonclient.Therearevariousadditionalmoduleswhichcanbeadded,likeforexamplegrizzlyorapacheconnector(seedependenciessnippedbelow).JerseyclientrunsbydefaultwithplainJDK(usingHttpUrlConnection).SeeChapter5,ClientAPI.formoredetails.
Currentlyavailableconnectors:
2.3.4.Serversideapplicationonsupportedcontainers
ApartforastandardJAXRSServletbaseddeploymentthatworkswithanyServletcontainerthatsupportsServlet2.5andhigher,Jerseyprovidessupportforprogrammaticdeploymenttothefollowingcontainers:Grizzly2(HTTPandServlet),JDKHttpserverandSimpleHttpserver.Thischapterpresentsonlyrequiredmavendependencies,moreinformationcanbefoundinChapter4,DeployingaRESTfulWebService.
123456
javax.ws.rsjavax.ws.rsapi2.0provided
123456789
10111213
org.glassfish.jersey.containersjerseycontainerservlet2.3.1provided
org.glassfish.jersey.corejerseyclient2.3.1provided
123456789
101112
org.glassfish.jersey.containersjerseycontainerservlet2.3.1
org.glassfish.jersey.corejerseyclient2.3.1
12345
org.glassfish.jersey.corejerseyclient2.3.1
123456789
1011
org.glassfish.jersey.connectorsjerseygrizzlyconnector2.3.1
org.glassfish.jersey.connectorsjerseyapacheconnector2.3.1
123456789
101112131415
org.glassfish.jersey.containersjerseycontainergrizzly2http2.3.1
org.glassfish.jersey.containersjerseycontainergrizzly2servlet2.3.1
org.glassfish.jersey.containersjerseycontainerjdkhttp2.3.1
-
2.4.ListofmodulesThefollowingchaptersprovideanoverviewofallJerseymodulesandtheirdependencieswithlinkstotherespectivebinaries(followalinkonamodulenametogetcompletesetofdownloadabledependencies).
Table2.1.JerseyCore
Core
jerseyclient Jerseycoreclientimplementation.
jerseycommon Jerseycorecommonpackages.
jerseyserver Jerseycoreserverimplementation.
Table2.2.JerseyContainers
Containers
jerseycontainergrizzly2http Grizzly2HttpContainer.
jerseycontainergrizzly2servlet Grizzly2ServletContainer.
jerseycontainerjdkhttp JDKHttpContainer.
jerseycontainerservlet JerseycoreServlet3.ximplementation.
jerseycontainerservletcore JerseycoreServlet2.ximplementation.
jerseycontainersimplehttp SimpleHttpContainer.
Table2.3.JerseyConnectors
Connectors
jerseygrizzlyconnector JerseyClientTransportviaGrizzly.
jerseyapacheconnector JerseyClientTransportviaApache.
Table2.4.JerseyMedia
Media
jerseymediajsonjackson JerseyJSONJacksonentityproviderssupportmodule.
jerseymediajsonjettison JerseyJSONJettisonentityproviderssupportmodule.
jerseymediajsonprocessing JerseyJSONP(JSR353)entityproviderssupportproxymodule.
jerseymediamoxy JerseyJSONentityproviderssupportmodulebasedonEclipseLinkMOXy.
jerseymediamultipart JerseyMultipartentityproviderssupportmodule.
jerseymediasse JerseyServerSentEventsentityproviderssupportmodule.
Table2.5.JerseyExtensions
Extensions
jerseybeanvalidation JerseyextensionmoduleprovidingsupportforBeanValidation(JSR349)API.
jerseymvc JerseyextensionmoduleprovidingsupportforMVC.
jerseymvcfreemarker JerseyextensionmoduleprovidingsupportforFreemarkertemplates.
jerseymvcjsp JerseyextensionmoduleprovidingsupportforJSPtemplates.
jerseyproxyclient Jerseyextensionmoduleprovidingsupportfor(proxybased)highlevelclientAPI.
jerseyservletportability LibrarythatenableswritingwebapplicationsthatrunwithbothJersey1.xandJersey2.xservletcontainers.
jerseywadldoclet Adocletthatgeneratesaresourcedocxmlfile:thisfilecontainsthejavadocdocumentationofresourceclasses,sothatthiscanbeusedforextendinggeneratedwadlwithusefuldocumentation.
Table2.6.JerseyTestFramework
TestFramework
jerseytestframeworkcore JerseyTestFrameworkCore.
jerseytestframeworkproviderbundle JerseyTestFrameworkProvidersBundle.
jerseytestframeworkproviderdefaultclient JerseyTestFrameworkDefaultClientProvider.
jerseytestframeworkproviderexternal JerseyTestFrameworkExternalcontainer.
jerseytestframeworkprovidergrizzly2 JerseyTestFrameworkGrizzly2container.
jerseytestframeworkproviderinmemory JerseyTestFrameworkInMemorycontainer.
jerseytestframeworkproviderjdkhttp JerseyTestFrameworkJDKHTTPcontainer.
jerseytestframeworkprovidersimple JerseyTestFrameworkSimpleHTTPcontainer.
1617181920
org.glassfish.jersey.containersjerseycontainersimplehttp2.3.1
-
Table2.7.JerseyGlassfishBundles
GlassfishBundles
jerseygfcdi JerseyCDIforGlassFishintegration.
jerseygfejb JerseyEJBforGlassFishintegration.
Table2.8.JerseyExamples
Examples
clipboard Jerseyclipboardexample.
clipboardprogrammatic JerseyprogrammaticresourceAPIclipboardexample.
exceptionmapping Jerseyexampleshowingexceptionmappersinaction.
helloworld Jerseyannotatedresourceclass"Helloworld"example.
helloworldprogrammatic JerseyprogrammaticresourceAPI"Helloworld"example.
helloworldpurejaxrs ExampleusingonlythestandardJAXRSAPI'sandthelightweightHTTPserverbundledinJDK.
httptrace JerseyHTTPTRACEsupportexample
httpsclientservergrizzly JerseyHTTPSClient/ServerexampleonGrizzly.
jaxb JerseyJAXBexample.
jaxrstypesinjection JerseyJAXRStypesinjectionexample.
jsonjackson JerseyJSONwithJacksonexample.
jsonjettison JerseyJSONwithJettisonJAXBexample.
jsonmoxy JerseyJSONwithMOXyexample.
jsonwithpadding JerseyJSONwithPaddingexample.
managedclient Jerseymanagedclientexample.
osgihelloworldwebapp OSGiHelloworld.
osgihelloworldwebapp OSGiHelloworldbundle.
osgihelloworldwebapp OSGiHelloworldwar.
osgihttpservice OSGiHelloworld.
osgihttpservice OSGiHelloworld.
reload Jerseyresourceconfigurationreloadexample.
serverasync JerseyJAXRSasynchronousserversideexample.
serverasyncmanaged JerseyJAXRSasynchronousserversideexamplewithcustomJerseyexecutorproviders.
serverasyncstandalone StandaloneJerseyJAXRSasynchronousserversideprocessingexample.
serversentevents JerseyServerSentEventsexample.
simpleconsole JerseySimpleConsoleexample.
ssetwitteraggregator JerseySSETwitterMessageAggregatorExample.
systempropertiesexample Jerseysystempropertiesexample.
xmlmoxy JerseyXMLMOXyexample.
Table2.9.JerseyExamplesWebApps
ExamplesWAR
beanvalidationwebapp JerseyBeanValidation(JSR349)example.
bookmark JerseyBookmarkexample.
bookmarkem JerseyBookmarkexampleusingEntityManager.
bookstorewebapp JerseyMVCBookstoreexample.
cdiwebapp JerseyCDIexample.
extendedwadlwebapp ExtendedWADLexample.
freemarkerwebapp JerseyFreemarkerexample.
helloworldwebapp Jerseyannotatedresourceclass"Helloworld"example.
httpsserverglassfish JerseyHTTPSserveronGlassFishexample.
jerseyejb JerseyEJBexample.
jsonprocessingwebapp JerseyJSONP(JSR353)example.
managedbeanswebapp JerseyManagedBeansWebApplicationexample.
managedclientsimplewebapp JerseyManagedClientSimpleWebappexample.
managedclientwebapp Jerseymanagedclientwebapplicationexample.
multipartwebapp JerseyMultipartexample.
sseitemstorewebapp JerseySSEbaseditemstoreexample.
Chapter3.JAXRSApplication,ResourcesandSubResources
TableofContents
3.1.RootResourceClasses3.1.1.@Path
-
3.1.2.@GET,@PUT,@POST,@DELETE,...(HTTPMethods)[email protected].@Consumes
3.2.ParameterAnnotations(@*Param)3.3.Subresources3.4.LifecycleofRootResourceClasses3.5.RulesofInjection3.6.Useof@Context3.7.Programmaticresourcemodel
ThischapterpresentsanoverviewofthecoreJAXRSconceptsresourcesandsubresources.
TheJAXRS2.0JavaDoccanbefoundonlinehere.
TheJAXRS2.0specificationdraftcanbefoundonlinehere.
3.1.RootResourceClasses
RootresourceclassesarePOJOs(PlainOldJavaObjects)thatareannotatedwith@Pathhaveatleastonemethodannotatedwith@Pathoraresourcemethoddesignatorannotationsuchas@GET,@PUT,@POST,@DELETE.Resourcemethodsaremethodsofaresourceclassannotatedwitharesourcemethoddesignator.ThissectionshowshowtouseJerseytoannotateJavaobjectstocreateRESTfulwebservices.
ThefollowingcodeexampleisaverysimpleexampleofarootresourceclassusingJAXRSannotations.TheexamplecodeshownhereisfromoneofthesamplesthatshipswithJersey,thezipfileofwhichcanbefoundinthemavenrepositoryhere.
Example3.1.Simplehelloworldrootresourceclass
Let'slookatsomeoftheJAXRSannotationsusedinthisexample.
3.1.1.@Path
The@Pathannotation'svalueisarelativeURIpath.Intheexampleabove,theJavaclasswillbehostedattheURIpath/helloworld.Thisisanextremelysimpleuseofthe@Pathannotation.WhatmakesJAXRSsousefulisthatyoucanembedvariablesintheURIs.
URIpathtemplatesareURIswithvariablesembeddedwithintheURIsyntax.ThesevariablesaresubstitutedatruntimeinorderforaresourcetorespondtoarequestbasedonthesubstitutedURI.Variablesaredenotedbycurlybraces.Forexample,lookatthefollowing@Pathannotation:
Inthistypeofexample,auserwillbepromptedtoentertheirname,andthenaJerseywebserviceconfiguredtorespondtorequeststothisURIpathtemplatewillrespond.Forexample,iftheuserenteredtheirusernameas"Galileo",thewebservicewillrespondtothefollowingURL:http://example.com/users/Galileo
Toobtainthevalueoftheusernamevariablethe@PathParammaybeusedonmethodparameterofarequestmethod,forexample:
Example3.2.SpecifyingURIpathparameter
Ifitisrequiredthatausernamemustonlyconsistofloweranduppercasenumericcharactersthenitispossibletodeclareaparticularregularexpression,whichoverridesthedefaultregularexpression,"[^/]+?",forexample:
Inthistypeofexampletheusernamevariablewillonlymatchusernamesthatbeginwithoneupperorlowercaseletterandzeroormorealphanumericcharactersandtheunderscorecharacter.Ifausernamedoesnotmatchthata404(NotFound)responsewilloccur.
A@Pathvaluemayormaynotbeginwitha'/',itmakesnodifference.Likewise,bydefault,a@Pathvaluemayormaynotendina'/',itmakesnodifference,andthusrequestURLsthatendordonotendina'/'willbothbematched.
3.1.2.@GET,@PUT,@POST,@DELETE,...(HTTPMethods)
@GET,@PUT,@POST,@DELETEand@HEADareresourcemethoddesignatorannotationsdefinedbyJAXRSandwhichcorrespondtothesimilarlynamedHTTPmethods.Intheexampleabove,theannotatedJavamethodwillprocessHTTPGETrequests.ThebehaviorofaresourceisdeterminedbywhichoftheHTTPmethodstheresourceisrespondingto.
ThefollowingexampleisanextractfromthestorageservicesamplethatshowstheuseofthePUTmethodtocreateorupdateastoragecontainer:
Example3.3.PUTmethod
123456789
10111213141516
packageorg.glassfish.jersey.examples.helloworldimportjavax.ws.rs.GETimportjavax.ws.rs.Pathimportjavax.ws.rs.Produces@Path("helloworld")publicclassHelloWorldResource{publicstaticfinalStringCLICHED_MESSAGE="HelloWorld!"@GET@Produces("text/plain")publicStringgetHello(){returnCLICHED_MESSAGE}}
@Path("/users/{username}")
123456789
@Path("/users/{username}")publicclassUserResource{@GET@Produces("text/xml")publicStringgetUser(@PathParam("username")StringuserName){...}}
1 @Path("users/{username:[azAZ][azAZ_09]*}")
1234567
@PUTpublicResponseputContainer(){System.out.println("PUTCONTAINER"+container)URIuri=uriInfo.getAbsolutePath()Containerc=newContainer(container,uri.toString())
-
BydefaulttheJAXRSruntimewillautomaticallysupportthemethodsHEADandOPTIONS,ifnotexplicitlyimplemented.ForHEADtheruntimewillinvoketheimplementedGETmethod(ifpresent)andignoretheresponseentity(ifset).AresponsereturnedfortheOPTIONSmethoddependsontherequestedmediatypedefinedinthe'Accept'header.TheOPTIONSmethodcanreturnaresponsewithasetofsupportedresourcemethodsinthe'Allow'headerorreturnaWADLdocument.Seewadlsectionformoreinformation.
3.1.3.@Produces
The@ProducesannotationisusedtospecifytheMIMEmediatypesofrepresentationsaresourcecanproduceandsendbacktotheclient.Inthisexample,theJavamethodwillproducerepresentationsidentifiedbytheMIMEmediatype"text/plain"[email protected]'sanexample:
Example3.4.SpecifyingoutputMIMEtype
ThedoGetAsPlainTextmethoddefaultstotheMIMEtypeofthe@Producesannotationattheclasslevel.ThedoGetAsHtmlmethod's@Producesannotationoverridestheclasslevel@Producessetting,andspecifiesthatthemethodcanproduceHTMLratherthanplaintext.
IfaresourceclassiscapableofproducingmorethatoneMIMEmediatypethentheresourcemethodchosenwillcorrespondtothemostacceptablemediatypeasdeclaredbytheclient.MorespecificallytheAcceptheaderoftheHTTPrequestdeclareswhatismostacceptable.ForexampleiftheAcceptheaderis"Accept:text/plain"thenthedoGetAsPlainTextmethodwillbeinvoked.AlternativelyiftheAcceptheaderis"Accept:text/plainq=0.9,text/html",whichdeclaresthattheclientcanacceptmediatypesof"text/plain"and"text/html"butprefersthelatter,thenthedoGetAsHtmlmethodwillbeinvoked.
Morethanonemediatypemaybedeclaredinthesame@Producesdeclaration,forexample:
Example3.5.UsingmultipleoutputMIMEtypes
ThedoGetAsXmlOrJsonmethodwillgetinvokedifeitherofthemediatypes"application/xml"and"application/json"areacceptable.Ifbothareequallyacceptablethentheformerwillbechosenbecauseitoccursfirst.
Optionally,servercanalsospecifythequalityfactorforindividualmediatypes.Theseareconsideredifseveralareequallyacceptablebytheclient.Forexample:
Example3.6.Serversidecontentnegotiation
Intheabovesample,ifclientacceptsboth"application/xml"and"application/json"(equally),thenaserveralwayssends"application/json",since"application/xml"hasalowerqualityfactor.
TheexamplesaboverefersexplicitlytoMIMEmediatypesforclarity.Itispossibletorefertoconstantvalues,whichmayreducetypographicalerrors,seetheconstantfieldvaluesofMediaType.
3.1.4.@Consumes
The@ConsumesannotationisusedtospecifytheMIMEmediatypesofrepresentationsthatcanbeconsumedbyaresource.Theaboveexamplecanbemodifiedtosettheclichedmessageasfollows:
Example3.7.SpecifyinginputMIMEtype
Inthisexample,theJavamethodwillconsumerepresentationsidentifiedbytheMIMEmediatype"text/plain".Noticethattheresourcemethodreturnsvoid.Thismeansnorepresentationisreturnedandresponsewithastatuscodeof204(NoContent)willbereturnedtotheclient.
@Consumescanbeappliedatboththeclassandthemethodlevelsandmorethanonemediatypemaybedeclaredinthesame@Consumesdeclaration.
3.2.ParameterAnnotations(@*Param)
Parametersofaresourcemethodmaybeannotatedwithparameterbasedannotationstoextractinformationfromarequest.Oneofthepreviousexamples
89
1011121314151617
Responserif(!MemoryStore.MS.hasContainer(c)){r=Response.created(uri).build()}else{r=Response.noContent().build()}MemoryStore.MS.createContainer(c)returnr}
123456789
1011121314
@Path("/myResource")@Produces("text/plain")publicclassSomeResource{@GETpublicStringdoGetAsPlainText(){...}@GET@Produces("text/html")publicStringdoGetAsHtml(){...}}
12345
@GET@Produces({"application/xml","application/json"})publicStringdoGetAsXmlOrJson(){...}
12345
@GET@Produces({"application/xmlqs=0.9","application/json"})publicStringdoGetAsXmlOrJson(){...}
12345
@POST@Consumes("text/plain")publicvoidpostClichedMessage(Stringmessage){//Storethemessage}
-
presentedtheuseof@PathParamtoextractapathparameterfromthepathcomponentoftherequestURLthatmatchedthepathdeclaredin@Path.
@QueryParamisusedtoextractqueryparametersfromtheQuerycomponentoftherequestURL.Thefollowingexampleisanextractfromthesparklinessample:
Example3.8.Queryparameters
Ifaqueryparameter"step"existsinthequerycomponentoftherequestURIthenthe"step"valuewillbewillextractedandparsedasa32bitsignedintegerandassignedtothestepmethodparameter.If"step"doesnotexistthenadefaultvalueof2,asdeclaredinthe@DefaultValueannotation,willbeassignedtothestepmethodparameter.Ifthe"step"valuecannotbeparsedasa32bitsignedintegerthenaHTTP404(NotFound)responseisreturned.UserdefinedJavatypessuchasColorParammaybeused,whichasimplementedasfollows:
Example3.9.CustomJavatypeforconsumingrequestparameters
IngeneraltheJavatypeofthemethodparametermay:
1. Beaprimitivetype
2. HaveaconstructorthatacceptsasingleStringargument
3. HaveastaticmethodnamedvalueOforfromStringthatacceptsasingleStringargument(see,forexample,Integer.valueOf(String)andjava.util.UUID.fromString(String))
4. Havearegisteredimplementationofjavax.ws.rs.ext.ParamConverterProviderJAXRSextensionSPIthatreturnsajavax.ws.rs.ext.ParamConverterinstancecapableofa"fromstring"conversionforthetype.or
5. BeList,SetorSortedSet,whereTsatisfies2or3above.Theresultingcollectionisreadonly.
Sometimesparametersmaycontainmorethanonevalueforthesamename.Ifthisisthecasethentypesin5)maybeusedtoobtainallvalues.
Ifthe@DefaultValueisnotusedinconjunctionwith@QueryParamandthequeryparameterisnotpresentintherequestthenvaluewillbeanemptycollectionforList,SetorSortedSet,nullforotherobjecttypes,andtheJavadefineddefaultforprimitivetypes.
The@PathParamandtheotherparameterbasedannotations,@MatrixParam,@HeaderParam,@CookieParam,@FormParamobeythesamerulesas@QueryParam.@MatrixParamextractsinformationfromURLpathsegments.@HeaderParamextractsinformationfromtheHTTPheaders.@CookieParamextractsinformationfromthecookiesdeclaredincookierelatedHTTPheaders.
@FormParamisslightlyspecialbecauseitextractsinformationfromarequestrepresentationthatisoftheMIMEmediatype"application/xwwwformurlencoded"andconformstotheencodingspecifiedbyHTMLforms,asdescribedhere.ThisparameterisveryusefulforextractinginformationthatisPOSTedbyHTMLforms,forexamplethefollowingextractstheformparameternamed"name"fromthePOSTedformdata:
Example3.10.ProcessingPOSTedHTMLform
Ifitisnecessarytoobtainageneralmapofparameternametovaluesthen,forqueryandpathparametersitispossibletodothefollowing:
Example3.11.ObtaininggeneralmapofURIpathand/orqueryparameters
Forheaderandcookieparametersthefollowing:
123456789
101112
@Path("smooth")@GETpublicResponsesmooth(@DefaultValue("2")@QueryParam("step")intstep,@DefaultValue("true")@QueryParam("minm")booleanhasMin,@DefaultValue("true")@QueryParam("maxm")booleanhasMax,@DefaultValue("true")@QueryParam("lastm")booleanhasLast,@DefaultValue("blue")@QueryParam("mincolor")ColorParamminColor,@DefaultValue("green")@QueryParam("maxcolor")ColorParammaxColor,@DefaultValue("red")@QueryParam("lastcolor")ColorParamlastColor){...}
123456789
101112131415161718192021222324
publicclassColorParamextendsColor{publicColorParam(Strings){super(getRGB(s))}privatestaticintgetRGB(Strings){if(s.charAt(0)=='#'){try{Colorc=Color.decode("0x"+s.substring(1))returnc.getRGB()}catch(NumberFormatExceptione){thrownewWebApplicationException(400)}}else{try{Fieldf=Color.class.getField(s)return((Color)f.get(null)).getRGB()}catch(Exceptione){thrownewWebApplicationException(400)}}}}
12345
@POST@Consumes("application/xwwwformurlencoded")publicvoidpost(@FormParam("name")Stringname){//Storethemessage}
12345
@GETpublicStringget(@ContextUriInfoui){MultivaluedMapqueryParams=ui.getQueryParameters()MultivaluedMappathParams=ui.getPathParameters()}
-
Example3.12.Obtaininggeneralmapofheaderparameters
Ingeneral@ContextcanbeusedtoobtaincontextualJavatypesrelatedtotherequestorresponse.
Becauseformparameters(unlikeothers)arepartofthemessageentity,itispossibletodothefollowing:
Example3.13.Obtaininggeneralmapofformparameters
I.e.youdon'tneedtousethe@Contextannotation.
Anotherkindofinjectionisthe@BeanParamwhichallowstoinjecttheparametersdescribedaboveintoasinglebean.Abeanannotatedwith@BeanParamcontaininganyfieldsandappropriate*paramannotation(like@PathParam)willbeinitializedwithcorrespondingrequestvaluesinexpectedwayasifthesefieldswereintheresourceclass.Theninsteadofinjectingrequestvalueslikepathparamintoaconstructorparametersorclassfieldsthe@BeanParamcanbeusedtoinjectsuchabeanintoaresourceorresourcemethod.The@BeanParamisusedthiswaytoaggregatemorerequestparametersintoasinglebean.
Example3.14.Exampleofthebeanwhichwillbeusedas@BeanParam
Example3.15.InjectionofMyBeanParamasamethodparameter:
Theexampleshowsaggregationofinjections@PathParam,@QueryParam@MatrixParamand@HeaderParamintoonesinglebean.Therulesforinjectionsinsidethebeanarethesameasdescribedabovefortheseinjections.The@DefaultValueisusedtodefinethedefaultvalueformatrixparametermatrixParam.Alsothe@Encodedannotationhasthesamebehaviourasifitwereusedforinjectionintheresourcemethoddirectly.Injectingthebeanparameterinto@Singletonresourceclassfieldsisnotallowed(injectionsintomethodparametermustbeusedinstead).
@BeanParamcancontainallparametersinjectionsinjections(@PathParam,@QueryParam,@MatrixParam,@HeaderParam,@CookieParam,@FormParam).Morebeanscanbeinjectedintooneresourceormethodparameterseveniftheyinjectthesamerequestvalues.Forexamplethefollowingispossible:
Example3.16.Injectionofmorebeansintooneresourcemethods:
3.3.Subresources
@Pathmaybeusedonclassesandsuchclassesarereferredtoasrootresourceclasses.@Pathmayalsobeusedonmethodsofrootresourceclasses.Thisenablescommonfunctionalityforanumberofresourcestobegroupedtogetherandpotentiallyreused.
Thefirstway@Pathmaybeusedisonresourcemethodsandsuchmethodsarereferredtoassubresourcemethods.Thefollowingexampleshowsthemethodsignaturesforarootresourceclassfromthejmakibackendsample:
Example3.17.Subresourcemethods
12345
@GETpublicStringget(@ContextHttpHeadershh){MultivaluedMapheaderParams=hh.getRequestHeaders()MappathParams=hh.getCookies()}
12345
@POST@Consumes("application/xwwwformurlencoded")publicvoidpost(MultivaluedMapformParams){//Storethemessage}
123456789
1011121314151617181920212223
publicclassMyBeanParam{@PathParam("p")privateStringpathParam@MatrixParam("m")@Encoded@DefaultValue("default")privateStringmatrixParam@HeaderParam("header")privateStringheaderParamprivateStringqueryParampublicMyBeanParam(@QueryParam("q")StringqueryParam){this.queryParam=queryParam}publicStringgetPathParam(){returnpathParam}...}
12345
@POSTpublicvoidpost(@BeanParamMyBeanParambeanParam,Stringentity){finalStringpathParam=beanParam.getPathParam()//containsinjectedpathparameter"p"...}
123456
@POSTpublicvoidpost(@BeanParamMyBeanParambeanParam,@BeanParamAnotherBeananotherBean,@PathParam("p")pathParam,Stringentity){//beanParam.getPathParam()==pathParam...}
123456789
@Singleton@Path("/printers")publicclassPrintersResource{@GET@Produces({"application/json","application/xml"})publicWebResourceListgetMyResources(){...}@GET@Path("/list")
-
IfthepathoftherequestURLis"printers"thentheresourcemethodsnotannotatedwith@Pathwillbeselected.IftherequestpathoftherequestURLis"printers/list"thenfirsttherootresourceclasswillbematchedandthenthesubresourcemethodsthatmatch"list"willbeselected,whichinthiscaseisthesubresourcemethodgetListOfPrinters.So,inthisexamplehierarchicalmatchingonthepathoftherequestURLisperformed.
Thesecondway@Pathmaybeusedisonmethodsnotannotatedwithresourcemethoddesignatorssuchas@GETor@POST.Suchmethodsarereferredtoassubresourcelocators.Thefollowingexampleshowsthemethodsignaturesforarootresourceclassandaresourceclassfromtheoptimisticconcurrencysample:
Example3.18.Subresourcelocators
TherootresourceclassItemResourcecontainsthesubresourcelocatormethodgetItemContentResourcethatreturnsanewresourceclass.IfthepathoftherequestURLis"item/content"thenfirstofalltherootresourcewillbematched,thenthesubresourcelocatorwillbematchedandinvoked,whichreturnsaninstanceoftheItemContentResourceresourceclass.Subresourcelocatorsenablereuseofresourceclasses.Amethodcanbeannotatedwiththe@Pathannotationwithemptypath(@Path("/")or@Path(""))whichmeansthatthesubresourcelocatorismatchedforthepathoftheenclosingresource(withoutsubresourcepath).
Example3.19.Subresourcelocatorswithemptypath
IntheexampleabovethesubresourcelocatormethodgetItemContentResourceismatchedforexampleforrequestpath"/item/locator"orevenforonly"/item".
Inadditiontheprocessingofresourceclassesreturnedbysubresourcelocatorsisperformedatruntimethusitispossibletosupportpolymorphism.Asubresourcelocatormayreturndifferentsubtypesdependingontherequest(forexampleasubresourcelocatorcouldreturndifferentsubtypesdependentontheroleoftheprinciplethatisauthenticated).Soforexamplethefollowingsubresourcelocatorisvalid:
Example3.20.Subresourcelocatorsreturningsubtype
Notethattheruntimewillnotmanagethelifecycleorperformanyfieldinjectionontoinstancesreturnedfromsubresourcelocatormethods.Thisisbecausetheruntimedoesnotknowwhatthelifecycleoftheinstanceis.IfitisrequiredthattheruntimemanagesthesubresourcesasstandardresourcestheClassshouldbereturnedasshowninthefollowingexample:
Example3.21.Subresourcelocatorscreatedfromclasses
10111213141516171819202122232425262728293031
@Produces({"application/json","application/xml"})publicWebResourceListgetListOfPrinters(){...}@GET@Path("/jMakiTable")@Produces("application/json")publicPrinterTableModelgetTable(){...}@GET@Path("/jMakiTree")@Produces("application/json")publicTreeModelgetTree(){...}@GET@Path("/ids/{printerid}")@Produces({"application/json","application/xml"})publicPrintergetPrinter(@PathParam("printerid")StringprinterId){...}@PUT@Path("/ids/{printerid}")@Consumes({"application/json","application/xml"})publicvoidputPrinter(@PathParam("printerid")StringprinterId,Printerprinter){...}@DELETE@Path("/ids/{printerid}")publicvoiddeletePrinter(@PathParam("printerid")StringprinterId){...}}
123456789
10111213141516171819202122232425262728
@Path("/item")publicclassItemResource{@ContextUriInfouriInfo@Path("content")publicItemContentResourcegetItemContentResource(){returnnewItemContentResource()}@GET@Produces("application/xml")publicItemget(){...}}}publicclassItemContentResource{@GETpublicResponseget(){...}@PUT@Path("{version}")publicvoidput(@PathParam("version")intversion,@ContextHttpHeadersheaders,byte[]in){...}}
12345678
@Path("/item")publicclassItemResource{@Path("/")publicItemContentResourcegetItemContentResource(){returnnewItemContentResource()}}
12345678
@Path("/item")publicclassItemResource{@Path("/")publicObjectgetItemContentResource(){returnnewAnyResource()}}
-
JAXRSresourcesaremanagedinperrequestscopebydefaultwhichmeansthatnewresourceiscreatedforeachrequest.Inthisexamplethejavax.inject.Singletonannotationsaysthattheresourcewillbemanagedassingletonandnotinrequestscope.Thesubresourcelocatormethodreturnsaclasswhichmeansthattheruntimewillmanagedtheresourceinstanceanditslifecycle.Ifthemethodwouldreturninstanceinstead,theSingletonannotationwouldhavenoeffectandthereturnedinstancewouldbeused.
Thesubresourcelocatorcanalsoreturnaprogrammaticresourcemodel.Seeresourcebuildersectionforinformationofhowtheprogrammaticresourcemodelisconstructed.Thefollowingexampleshowsverysimpleresourcereturnedfromthesubresourcelocatormethod.
Example3.22.Subresourcelocatorsreturningresourcemodel
Thecodeabovehasexactlythesameeffectaspreviousexample.ResourceisaresourcesimpleresourceconstructedfromItemContentSingletonResource.Morecomplexprogrammaticresourcecanbereturnedaslongtheyarevalidresources.
3.4.LifecycleofRootResourceClasses
Bydefaultthelifecycleofrootresourceclassesisperrequestwhich,namelythatanewinstanceofarootresourceclassiscreatedeverytimetherequestURIpathmatchestherootresource.Thismakesforaverynaturalprogrammingmodelwhereconstructorsandfieldscanbeutilized(asintheprevioussectionshowingtheconstructoroftheSparklinesResourceclass)withoutconcernformultipleconcurrentrequeststothesameresource.
Ingeneralthisisunlikelytobeacauseofperformanceissues.ClassconstructionandgarbagecollectionofJVMshasvastlyimprovedovertheyearsandmanyobjectswillbecreatedanddiscardedtoserveandprocesstheHTTPrequestandreturntheHTTPresponse.
InstancesofsingletonrootresourceclassescanbedeclaredbyaninstanceofApplication.
JerseysupportstwofurtherlifecyclesusingJerseyspecificannotations.
Table3.1.Resourcescopes
Scope Annotation Annotationfullclassname Description
Requestscope @RequestScoped(ornone) org.glassfish.jersey.process.internal.RequestScoped
Defaultlifecycle(appliedwhennoannotationispresent).Inthisscopetheresourceinstanceiscreatedforeachnewrequestandusedforprocessingofthisrequest.Iftheresourceisusedmorethanonetimeintherequestprocessing,alwaysthesameinstancewillbeused.Thiscanhappenwhenaresourceisasubresourceisreturnedmoretimesduringthematching.Inthissituationonlyoninstancewillservertherequests.
Perlookupscope @PerLookup org.glassfish.jersey.process.internal.RequestScoped
Inthisscopetheresourceinstanceiscreatedeverytimeitisneededfortheprocessingevenithandlesthesamerequest.
Singleton @Singleton javax.inject.Singleton
Inthisscopethereisonlyoneinstanceperjaxrsapplication.Singletonresourcecanbeeitherannotatedwith@SingletonanditsclasscanberegisteredusingtheinstanceofApplication.YoucanalsocreatesingletonsbyregisteringsingletoninstancesintoApplication.
3.5.RulesofInjectionPrevioussectionshavepresentedexamplesofannotatedtypes,mostlyannotatedmethodparametersbutalsoannotatedfieldsofaclass,fortheinjectionofvaluesontothosetypes.
Thissectionpresentstherulesofinjectionofvaluesonannotatedtypes.Injectioncanbeperformedonfields,constructorparameters,resource/subresource/subresourcelocatormethodparametersandbeansettermethods.Thefollowingpresentsanexampleofallsuchinjectioncases:
Example3.23.Injection
123456789
1011121314
importjavax.inject.Singleton@Path("/item")publicclassItemResource{@Path("content")publicClassgetItemContentResource(){returnItemContentSingletonResource.class}}@SingletonpublicclassItemContentSingletonResource{//thisclassismanagedinthesingletonlifecycle}
123456789
10
importorg.glassfish.jersey.server.model.Resource@Path("/item")publicclassItemResource{@Path("content")publicResourcegetItemContentResource(){returnResource.from(ItemContentSingletonResource.class)}}
123456789
1011121314151617181920
@Path("id:\d+")publicclassInjectedResource{//Injectionontofield@DefaultValue("q")@QueryParam("p")privateStringp//InjectionontoconstructorparameterpublicInjectedResource(@PathParam("id")intid){...}//Injectionontoresourcemethodparameter@GETpublicStringget(@ContextUriInfoui){...}//Injectionontosubresourceresourcemethodparameter@Path("subid")@GETpublicStringget(@PathParam("subid")Stringid){...}//Injectionontosubresourcelocatormethodparameter@Path("subid")
-
Therearesomerestrictionswheninjectingontoresourceclasseswithalifecycleofsingletonscope.Insuchcasestheclassfieldsorconstructorparameterscannotbeinjectedwithrequestspecificparameters.So,forexamplethefollowingisnotallowed.
Example3.24.Wronginjectionintoasingletonscope
Theexampleabovewillcausevalidationfailureduringapplicationinitializationassingletonresourcescannotinjectrequestspecificparameters.Thesameexamplewouldfailifthequeryparameterwouldbeinjectedintoconstructorparameterofsuchasingleton.Inotherwords,ifyouwishoneresourceinstancetoservermorerequests(inthesametime)itcannotbeboundtoaspecificrequestparameter.
Theexceptionexistsforspecificrequestobjectswhichcaninjectedevenintoconstructororclassfields.Fortheseobjectstheruntimewillinjectproxieswhichareabletosimultaneouslyservermorerequest.TheserequestobjectsareHttpHeaders,Request,UriInfo,SecurityContext.Theseproxiescanbeinjectedusingthe@Contextannotation.Thefollowingexampleshowsinjectionofproxiesintothesingletonresourceclass.
Example3.25.Injectionofproxiesintosingleton
Tosummarizetheinjectioncanbedoneintothefollowingconstructs:
Table3.2.Overviewofinjectiontypes
Javaconstruct Description
Classfields Injectvaluedirectlyintothefieldoftheclass.Thefieldcanbeprivateandmustnotbefinal.CannotbeusedinSingletonscopeexceptproxiabletypesmentionedabove.
Constructorparameters Theconstructorwillbeinvokedwithinjectedvalues.Ifmoreconstructorsexiststheonewiththemostinjectableparameterswillbeinvoked.CannotbeusedinSingletonscopeexceptproxiabletypesmentionedabove.
Resourcemethods Theresourcemethods(theseannotatedwith@GET,@POST,...)cancontainparametersthatcanbeinjectedwhentheresourcemethodisexecuted.Canbeusedinanyscope.
Subresourcelocators Thesubresourcelocators(methodsannotatedwith@Pathbutnot@GET,@POST,...)cancontainparametersthatcanbeinjectedwhentheresourcemethodisexecuted.Canbeusedinanyscope.
Settermethods
Insteadofinjectingvaluesdirectlyintofieldthevaluecanbeinjectedintothesettermethodwhichwillinitializethefield.Thisinjectioncanbeusedonlywith@Contextannotation.Thismeansitcannotbeusedforexampleforinjectingofqueryparamsbutitcanbeusedforinjectionsofrequest.Thesetterswillbecalledaftertheobjectcreationandonlyonce.Thenameofthemethoddoesnotnecessaryhaveasetterpattern.CannotbeusedinSingletonscopeexceptproxiabletypesmentionedabove.
Thefollowingexampleshowsallpossiblejavaconstructsintowhichthevaluescanbeinjected.
Example3.26.Exampleofpossibleinjections
212223242526
publicSubResourcegetSubResource(@PathParam("subid")Stringid){...}//Injectionusingbeansettermethod@HeaderParam("Xheader")publicvoidsetHeader(Stringheader){...}}
123456789
10111213
@Path("resource")@SingletonpublicstaticclassMySingletonResource{@QueryParam("query")Stringparam//WRONG:initializationofapplicationwillfailasyoucannot//injectrequestspecificparametersintoasingletonresource.@GETpublicStringget(){return"queryparam:"+param}}
123456789
101112131415
@Path("resource")@SingletonpublicstaticclassMySingletonResource{@ContextRequestrequest//thisisok:theproxyofRequestwillbeinjectedintothissingletonpublicMySingletonResource(@ContextSecurityContextsecurityContext){//thisisoktoo:theproxyofSecurityContextwillbeinjected}@GETpublicStringget(){return"queryparam:"+param}}
123456789
10111213141516171819202122232425
@Path("resource")publicstaticclassSummaryOfInjectionsResource{@QueryParam("query")Stringparam//injectionintoaclassfield@GETpublicStringget(@QueryParam("query")StringmethodQueryParam){//injectionintoaresourcemethodparameterreturn"queryparam:"+param}@Path("subresourcelocator")publicClasssubResourceLocator(@QueryParam("query")StringsubResourceQueryParam){//injectionintoasubresourcelocatorparameterreturnSubResource.class}publicSummaryOfInjectionsResource(@QueryParam("query")StringconstructorQueryParam){//injectionintoaconstructorparameter}@ContextpublicvoidsetRequest(Requestrequest){
-
The@FormParamannotationisspecialandmayonlybeutilizedonresourceandsubresourcemethods.Thisisbecauseitextractsinformationfromarequestentity.
3.6.Useof@Context
Previoussectionshaveintroducedtheuseof@Context.Chapter5oftheJAXRSspecificationpresentsallthestandardJAXRSJavatypesthatmaybeusedwith@Context.
WhendeployingaJAXRSapplicationusingservletthenServletConfig,ServletContext,HttpServletRequestandHttpServletResponseareavailableusing@Context.
3.7.ProgrammaticresourcemodelResourcescanbeconstructedfromclassesorinstancesbutalsocanbeconstructedfromaprogrammaticresourcemodel.Everyresourcecreatedfromfromresourceclassescanalsobeconstructedusingtheprogrammaticresourcebuilderapi.Seeresourcebuildersectionformoreinformation.
Chapter4.DeployingaRESTfulWebService
TableofContents
4.1.AutoDiscoverableFeatures4.1.1.ConfiguringtheFeatureAutodiscoverymechanism
4.2.Turnoffclasspathscanning
JAXRSprovidesadeploymentagnosticabstractclassApplicationfordeclaringrootresourceandproviderclasses,androotresourceandprovidersingletoninstances.AWebservicemayextendthisclasstodeclarerootresourceandproviderclasses.Forexample,
Example4.1.Deploymentagnosticapplicationmodel
AlternativelyitispossibletoreuseoneofJersey'simplementationsthatscansforrootresourceandproviderclassesgivenaclasspathorasetofpackagenames.SuchclassesareautomaticallyaddedtothesetofclassesthatarereturnedbygetClasses.Forexample,thefollowingscansforrootresourceandproviderclassesinpackages"org.foo.rest","org.bar.rest"andinanysubpackagesofthosetwo:
Example4.2.ReusingJerseyimplementationinyourcustomapplicationmodel
TherearemultipledeploymentoptionsfortheclassthatimplementsApplicationinterfaceintheServlet3.0container.Forsimpledeployments,noweb.xmlisneededatall.Instead,an@ApplicationPathannotationcanbeusedtoannotatetheuserdefinedapplicationclassandspecifythebaseresourceURIofallapplicationresources:
Example4.3.DeploymentofaJAXRSapplicationusing@ApplicationPathwithServlet3.0
PleasenotethatthereismorewhichcanbesetorcalledduringexecutionofResourceConfigdescendantsconstructor,seeResourceConfigjavadocformoredetails.
YoualsoneedtosetmavenwarpluginattributefailOnMissingWebXmltofalseinpom.xmlwhenbuilding.warwithoutweb.xmlfileusingmaven:
Example4.4.Configurationofmavenwarplugininpom.xmlwithServlet3.0
AnotherdeploymentoptionistodeclareJAXRSapplicationdetailsintheweb.xml.Thisisusuallysuitableincaseofmorecomplexdeployments,e.g.when
2627282930313233343536
//injectionintoasettermethodSystem.out.println(request!=null)}}publicstaticclassSubResource{@GETpublicStringget(){return"subresource"}}
12345678
publicclassMyApplicationextendsApplication{@OverridepublicSet>s=newHashSetfalse...
-
securitymodelneedstobeproperlydefinedorwhenadditionalinitializationparametershavetobepassedtoJerseyruntime.JAXRS1.1specifiesthatafullyqualifiednameoftheclassthatimplementsApplicationmaybedeclaredintheelementoftheJAXRSapplication'sweb.xml.ThisissupportedinaWebcontainerimplementingServlet3.0asfollows:
Example4.5.DeploymentofaJAXRSapplicationusingweb.xmlwithServlet3.0
Notethattheelementisomittedfromtheservletdeclaration.ThisisacorrectdeclarationutilizingtheServlet3.0extensionmechanism.AlsonotethatisusedtodefinethebaseresourceURI.
WhenrunninginaServlet2.xtheninsteaditisnecessarytodeclaretheJerseyspecificservletandpasstheApplicationimplementationclassnameasoneoftheservlet'sinitparamentries:
Example4.6.DeploymentofyourapplicationusingJerseyspecificservlet
Ifthereisnoconfigurationtobesetanddeployedapplicationconsistsonlyfromresourcesandprovidersstoredinparticularpackages,Jerseycanscanthemandregisterautomatically:
Example4.7.UsingJerseyspecificservletwithoutanapplicationmodelinstance
JAXRSalsoprovidestheabilitytoobtainacontainerspecificartifactfromanApplicationinstance.Forexample,JerseysupportsusingGrizzlyasfollows:
JerseyalsoprovidesGrizzlyhelperclassestodeploytheHttpHandlerinstanceatabaseURLforinprocessdeployment.
TheJerseysamplesprovidemanyexamplesofServletbasedandGrizzlyinprocessbaseddeployments.
4.1.AutoDiscoverableFeatures
ForafewmodulesprovidedbyJerseythereisnoneedtoexplicitlyregistertheirFeaturesastheseFeaturesarediscoveredandregisteredintheConfiguration(onclient/server)automaticallybyJerseywhenthemodulesimplementingthesefeaturesarepresentontheclasspathduringtheanapplicationdeployment.Themodulesthatareautomaticallydiscoveredinclude:
jerseymediamoxy(JSONpart)
jerseymediajsonprocessing
jerseybeanvalidation
Besidesthesemodulestherearealsofewfeatures/providerspresentinjerseyservermodulethatarediscoveredbythismechanismandtheiravailabilityisaffectedbyJerseyautodiscoverysupportconfiguration(seeSection4.1.1,ConfiguringtheFeatureAutodiscoverymechanism):
WadlFeatureenablesWADLprocessing.
UriConnegFilteraURIbasedcontentnegotiationfilter.
Note
AutodiscoveryfunctionalityisinJerseysupportedbyimplementinganinternalSPIAutoDiscoverableinterface.Thisinterfaceisnotpublicatthemoment,sobecarefulwhenusingit.
4.1.1.ConfiguringtheFeatureAutodiscoverymechanism
TheautodiscoveryoffeaturesinJerseythatisenabledbydefaultcanbedisabledbyusingspecial(common/server/client)properties:
Commonautodiscoveryproperties
CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE
Disablesautodiscoverygloballyonclient/server.
123456789
1011
org.foo.rest.MyApplication...org.foo.rest.MyApplication/resources...
123456789
101112
JerseyWebApplicationorg.glassfish.jersey.servlet.ServletContainerjavax.ws.rs.Applicationorg.foo.rest.MyApplication......
123456789
101112
JerseyWebApplicationorg.glassfish.jersey.servlet.ServletContainerjersey.config.server.provider.packagesorg.foo.restorg.bar.rest......
1 HttpHandlerendpoint=RuntimeDelegate.getInstance().createEndpoint(newMyApplication(),HttpHandler.class)
-
CommonProperties.JSON_PROCESSING_FEATURE_DISABLE
DisablesconfigurationofJsonProcessing(JSR353)feature.
CommonProperties.MOXY_JSON_FEATURE_DISABLE
DisablesconfigurationofMOXyJsonfeature.
Foreachofthesepropertiesthereisaclient/servercounterpartthatonlydisablesthefeatureontheclientorserverrespectively(seeClientProperties/ServerProperties).Eachoftheseclient/serverspecificautodiscoveryrelatedpropertiesoverridesthevalueoftherelatedcommonproperty(ifset).
Note
Incaseanautodiscoverablefeatureisdisabledthenallthefeatured,componentsand/orproperties,registeredwiththefeaturebydefaultusingtheautodiscoverymechanismhavetoberegisteredmanually.
4.2.TurnoffclasspathscanningJerseyusescommonServiceLoaderorLookupdesignpatterntoobtainallserviceimplementations.ItmeansitlookupswholeclasspathtofindappropriatefilesinMETAINF/services/.Theclasspathlookupmaybetimeconsuming.Themorejarorwarfilesonclasspaththelookupislonger.Ifyoucountanymsofapplicationbootstrapyoucangenerallydisableserviceslookup.
JerseyislookingforimplementationoffollowingSPIs
AutoDiscoverable(server,client)itmeansifyoudisableserviceloadingtheAutoDiscoverablefeatureisautomaticallydisabledtoo
MessageBodyReader(server,client)
MessageBodyWriter(server,client)
HeaderDelegateProvider(server,client)
ComponentProvider(server)
ContainerProvider(server)
AsyncContextDelegateProvider(server/servlet)
InallcasesitispossibletoregisteranSPIimplementationclassorinstanceprogrammatically.ThereforeyoucandisableserviceslookupinJerseyandsavedozensofmsduringapplicationinitialization.TheserviceslookupinJerseythatisenabledbydefaultcanbedisabledbyusingspecialpropertyCommonProperties.METAINF_SERVICES_LOOKUP_DISABLE.Thereisaclient/servercounterpartthatonlydisablesthefeatureontheclientorserverrespectively:ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE/ServerProperties.METAINF_SERVICES_LOOKUP_DISABLE.Theclient/serverspecificpropertyoverridesthevalueoftherelatedcommonproperty(ifset).
Forexample,followingcodesnippetregistersdifferenttypesofimplementations:ContainerRequestFilter,Feature,ComponentProviderandContainerProvider:
Example4.8.RegisteringSPIimplementationsusingResourceConfig
Chapter5.ClientAPITableofContents
5.1.UniformInterfaceConstraint5.2.EaseofuseandreusingJAXRSartifacts5.3.OverviewoftheClientAPI
5.3.1.GettingstartedwiththeclientAPI5.3.2.CreatingandconfiguringaClientinstance5.3.3.Targetingawebresource5.3.4.IdentifyingresourceonWebTarget5.3.5.InvokingaHTTPrequest5.3.6.Examplesummary
5.4.Javainstancesandtypesforrepresentations5.4.1.Addingsupportfornewrepresentations
5.5.ClientTransportConnectors5.6.Usingclientrequestandresponsefilters5.7.Closingconnections5.8.SecuringaClient
5.8.1.HTTPBasicAuthenticationSupport5.8.2.HTTPDigestAuthenticationSupport
ThissectionintroducestheJAXRSClientAPI,whichisafluentJavabasedAPIforcommunicationwithRESTfulWebservices.ThisstandardAPIthatisalsopartofJavaEE7isdesignedtomakeitveryeasytoconsumeaWebserviceexposedviaHTTPprotocolandenablesdeveloperstoconciselyandefficientlyimplementportableclientsidesolutionsthatleverageexistingandwellestablishedclientsideHTTPconnectorimplementations.
TheJAXRSclientAPIcanbeutilizedtoconsumeanyWebserviceexposedontopofaHTTPprotocolorit'sextension(e.g.WebDAV),andisnotrestrictedtoservicesimplementedusingJAXRS.Yet,developersfamiliarwithJAXRSshouldfindtheclientAPIcomplementarytotheirservices,especiallyiftheclientAPIisutilizedbythoseservicesthemselves,ortotestthoseservices.TheJAXRSclientAPIfindsinspirationintheproprietaryJersey1.xClientAPIanddevelopersfamiliarwiththeJersey1.xClientAPIshouldfinditeasytounderstandalltheconceptsintroducedinthenewJAXRSClientAPI.
ThegoalsoftheclientAPIarethreefold:
1. EncapsulateakeyconstraintoftheRESTarchitecturalstyle,namelytheUniformInterfaceConstraintandassociateddataelements,asclientsideJavaartifacts
2. MakeitaseasytoconsumeRESTfulWebservicesexposedoverHTTP,sameastheJAXRSserversideAPImakesiteasytodevelopRESTfulWebservicesand
3. SharecommonconceptsandextensibilitypointsoftheJAXRSAPIbetweentheserverandtheclientsideprogrammingmodels.
123456
finalResourceConfigresourceConfig=newResourceConfig(MyResource.class)resourceConfig.register(org.glassfish.jersey.server.filter.UriConnegFilter.class)resourceConfig.register(org.glassfish.jersey.server.validation.ValidationFeature.class)resourceConfig.register(org.glassfish.jersey.server.spring.SpringComponentProvider.class)resourceConfig.register(org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainerProvider.class)resourceConfig.property(ServerProperties.METAINF_SERVICES_LOOKUP_DISABLE,true)
-
AsanextensiontothestandardJAXRSClientAPI,theJerseyClientAPIsupportsapluggablearchitecturetoenabletheuseofdifferentunderlyingHTTPclientConnectorimplementations.SeveralsuchimplementationsarecurrentlyprovidedwithJersey.WehaveadefaultclientconnectorusingHttp(s)URLConnectionsuppliedwiththeJDKaswellasconnectorimplementationsbasedonApacheHTTPClient,andGrizzlyAsynchronousClient.
5.1.UniformInterfaceConstraint
TheuniforminterfaceconstraintboundsthearchitectureofRESTfulWebservicessothataclient,suchasabrowser,canutilizethesameinterfacetocommunicatewithanyservice.ThisisaverypowerfulconceptinsoftwareengineeringthatmakesWebbasedsearchenginesandservicemashupspossible.Itinducespropertiessuchas:
1. simplicity,thearchitectureiseasiertounderstandandmaintainand
2. evolvabilityorloosecoupling,clientsandservicescanevolveovertimeperhapsinnewandunexpectedways,whileretainingbackwardscompatibility.
Furtherconstraintsarerequired:
1. everyresourceisidentifiedbyaURI
2. aclientinteractswiththeresourceviaHTTPrequestsandresponsesusingafixedsetofHTTPmethods
3. oneormorerepresentationscanbereturnedandareidentifiedbymediatypesand
4. thecontentsofwhichcanlinktofurtherresources.
TheaboveprocessrepeatedoverandagainshouldbefamiliartoanyonewhohasusedabrowsertofillinHTMLformsandfollowlinks.Thatsameprocessisapplicabletononbrowserbasedclients.
ManyexistingJavabasedclientAPIs,suchastheApacheHTTPclientAPIorHttpUrlConnectionsuppliedwiththeJDKplacetoomuchfocusontheClientServerconstraintfortheexchangesofrequestandresponsesratherthanaresource,identifiedbyaURI,andtheuseofafixedsetofHTTPmethods.
AresourceintheJAXRSclientAPIisaninstanceoftheJavaclassWebTarget.andencapsulatesanURI.ThefixedsetofHTTPmethodscanbeinvokedbasedontheWebTarget.TherepresentationsareJavatypes,instancesofwhich,maycontainlinksthatnewinstancesofWebTargetmaybecreatedfrom.
5.2.EaseofuseandreusingJAXRSartifactsSinceaJAXRScomponentisrepresentedasanannotatedJavatype,itmakesiteasytoconfigure,passaroundandinjectinwaysthatarenotsointuitiveorpossiblewithotherclientsideAPIs.TheJerseyClientAPIreusesmanyaspectsoftheJAXRSandtheJerseyimplementationsuchas:
1. URIbuildingusingUriBuilderandUriTemplatetosafelybuildURIs
2. BuiltinsupportforJavatypesofrepresentationssuchasbyte[],String,Number,Boolean,Character,InputStream,java.io.Reader,File,DataSource,JAXBbeansaswellasadditionalJerseyspecificJSONandMultiPartsupport.
3. UsingthefluentbuilderstyleAPIpatterntomakeiteasiertoconstructrequests.
SomeAPIs,liketheApacheHTTPClientorHttpURLConnectioncanberatherhardtouseand/orrequiretoomuchcodetodosomethingrelativelysimple,especiallywhentheclientneedstounderstanddifferentpayloadrepresentations.ThisiswhytheJerseyimplementationofJAXRSClientAPIprovidessupportforwrappingHttpUrlConnectionandtheApacheHTTPclient.ThusitispossibletogetthebenefitsoftheestablishedJAXRSimplementationsandfeatureswhilegettingtheeaseofusebenefitofthesimpledesignoftheJAXRSclientAPI.Forexample,withalowlevelHTTPclientlibrary,sendingaPOSTrequestwithabunchoftypedHTMLformparametersandreceivingaresponsedeserializedintoaJAXBbeanisnotstraightforwardatall.WiththenewJAXRSClientAPIsupportedbyJerseythistaskisveryeasy:
Example5.1.POSTrequestwithformparameters
IntheExample5.1,POSTrequestwithformparametersanewWebTargetinstanceiscreatedusinganewClientinstancefirst,nextaForminstanceiscreatedwithtwoformparameters.Onceready,theForminstanceisPOSTedtothetargetresource.First,theacceptablemediatypeisspecifiedintherequest(...)method.Theninthepost(...)method,acalltoastaticmethodonJAXRSEntityismadetoconstructtherequestentityinstanceandattachthepropercontentmediatypetotheformentitythatisbeingsent.Thesecondparameterinthepost(...)methodspecifiestheJavatypeoftheresponseentitythatshouldbereturnedfromthemethodincaseofasuccessfulresponse.InthiscaseaninstanceofJAXBbeanisrequestedtobereturnedonsuccess.TheJerseyclientAPItakescareofselectingtheproperMessageBodyWriterfortheserializationoftheForminstance,invokingthePOSTrequestandproducinganddeserializationoftheresponsemessagepayloadintoaninstanceofaJAXBbeanusingaproperMessageBodyReader.
IfthecodeabovehadtobewrittenusingHttpUrlConnection,thedeveloperwouldhavetowritecustomcodetoserializetheformdatathataresentwithinthePOSTrequestanddeserializetheresponseinputstreamintoaJAXBbean.Additionally,morecodewouldhavetobewrittentomakeiteasytoreusethelogicwhencommunicatingwiththesameresourcehttp://localhost:8080/resourcethatisrepresentedbytheJAXRSWebTargetinstanceinourexample.
5.3.OverviewoftheClientAPI
5.3.1.GettingstartedwiththeclientAPI
RefertothedependenciesfordetailsonthedependencieswhenusingtheJerseyJAXRSClientsupport.
YoumayalsowanttouseacustomConnectorimplementation.Insuchcaseyouwouldneedtoincludeadditionaldependenciesonthemodule(s)containingthecustomclientconnectorthatyouwanttouse.Seesection"ConfiguringcustomConnectors"abouthowtouseandconfigureacustomJerseyclienttransportConnector.
5.3.2.CreatingandconfiguringaClientinstance
JAXRSClientAPIisadesignedtoallowfluentprogrammingmodel.Thismeans,aconstructionofaClientinstance,fromwhichaWebTargetiscreated,fromwhicharequestInvocationisbuiltandinvokedcanbechainedinasingle"flow"ofinvocations.Theindividualstepsoftheflowwillbeshowninthefollowingsections.ToutilizetheclientAPIitisfirstnecessarytobuildaninstanceofaClientusingoneofthestaticClientBuilderfactorymethods.Here'sthemostsimpleexample:
TheClientBuilderisaJAXRSAPIusedtocreatenewinstancesofClient.Inaslightlymoreadvancedscenarios,ClientBuildercanbeusedto
123456789
1011
Clientclient=ClientBuilder.newClient()WebTargettarget=client.target("http://localhost:9998").path("resource")Formform=newForm()form.param("x","foo")form.param("y","bar")MyJAXBBeanbean=target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),MyJAXBBean.class)
1 Clientclient=ClientBuilder.newClient()
-
configureadditionalclientinstanceproperties,suchasaSSLtransportsettings,ifneeded(see???below).
AClientinstancecanbeconfiguredduringcreationbypassingaClientConfigtothenewClient(Configurable)ClientBuilderfactorymethod.ClientConfigimplementsConfigurableandthereforeitoffersmethodstoregisterproviders(e.g.featuresorindividualentityproviders,filtersorinterceptors)andsetupproperties.Thefollowingcodeshowsaregistrationofcustomclientfilters:
Intheexample,filtersareregisteredusingtheClientConfig.register(...)method.Therearemultipleoverloadedversionsofthemethodthatsupportregistrationoffeatureandproviderclassesorinstances.OnceaClientConfiginstanceisconfigured,itcanbepassedtotheClientBuildertocreateapreconfiguredClientinstance.
NotethattheJerseyClientConfigsupportsthefluentAPImodelofConfigurable.Withthatthecodethatconfiguresanewclientinstancecanbealsowrittenusingamorecompactstyleasshownbelow.
TheabilitytoleveragethiscompactpatternisinherenttoallJAXRSandJerseyClientAPIcomponents.
SinceClientimplementsConfigurableinterfacetoo,itcanbeconfiguredfurtherevenafterithasbeencreated.ImportantistomentionthatanyconfigurationchangedoneonaClientinstancewillnotinfluencetheClientConfiginstancethatwasusedtoprovidetheinitialClientinstanceconfigurationattheinstancecreationtime.ThenextpieceofcodeshowsaconfigurationofanexistingClientinstance.
Similarlytoearlierexamples,sinceClient.register(...)methodsupportsthefluentAPIstyle,multipleclientinstanceconfigurationcallscanbechained:
TogetthecurrentconfigurationoftheClientinstanceagetConfiguration()methodcanbeused.
Inthecode,anadditionalMyClientResponseFilterclassandAnotherClientFilterinstanceareregisteredintheclientConfig.TheclientConfigisthenusedtoconstructanewClientinstance.TheThirdClientFilterisaddedseparatelytotheconstructedClientinstance.ThisdoesnotinfluencetheconfigurationrepresentedbytheoriginalclientConfig.InthelaststepanewConfigurationisretrievedfromtheclient.ThisconfigurationcontainsallthreeregisteredfilterswhiletheoriginalclientConfiginstancestillcontainsonlytwofilters.UnlikeclientConfigcreatedseparately,thenewConfigurationretrievedfromtheclientinstancerepresentsaliveclientconfigurationview.AnyadditionalconfigurationchangesmadetotheclientinstancearealsoreflectedinthenewConfiguration.So,newConfigurationisreallyaviewoftheclientconfigurationandnotaconfigurationstatecopy.TheseprinciplesareimportantintheclientAPIandwillbeusedinthefollowingsectionstoo.Forexample,youcanconstructacommonbaseconfigurationforallclients(inourcaseitwouldbeclientConfig)andthenreusethiscommonconfigurationinstancetoconfiguremultipleclientinstancesthatcanbefurtherspecialized.Similarly,youcanuseanexistingclientinstanceconfigurationtoconfigureanotherclientinstancewithouthavingtoworryaboutanysideeffectsintheoriginalclientinstance.
5.3.3.Targetingawebresource
OnceyouhaveaClientinstanceyoucancreateaWebTargetfromit.
AClientcontainsseveraltarget(...)methodsthatallowforcreationofWebTargetinstance.Inthiscasewe'reusingtarget(Stringuri)version.TheuripassedtothemethodasaStringistheURIofthetargetedwebresource.InmorecomplexscenariositcouldbethecontextrootURIofthewholeRESTfulapplication,fromwhichWebTargetinstancesrepresentingindividualresourcetargetscanbederivedandindividuallyconfigured.Thisispossible,becauseJAXRSWebTargetalsoimplementsConfigurable:
TheconfigurationprinciplesusedinJAXRSclientAPIapplytoWebTargetaswell.EachWebTargetinstanceinheritsaconfigurationfromit'sparent(eitheraclientoranotherwebtarget)andcanbefurthercustomconfiguredwithoutaffectingtheconfigurationoftheparentcomponent.Inthiscase,theFilterForExampleComwillberegisteredonlyinthewebTargetandnotinclient.So,theclientcanstillbeusedtocreatenewWebTargetinstancespointingatotherURIsusingjustthecommonclientconfiguration,whichFilterForExampleComfilterisnotpartof.
5.3.4.IdentifyingresourceonWebTarget
Let'sassumewehaveawebTargetpointingat"http://example.com/rest"URIthatrepresentsacontextrootofaRESTfulapplicationandthereisaresourceexposedontheURI"http://example.com/rest/resource".Asalreadymentioned,aWebTargetinstancecanbeusedtoderiveotherwebtargets.Usethefollowingcodetodefineapathtotheresource.
TheresourceWebTargetnowpointstotheresourceonURI"http://example.com/rest/resource".AgainifweconfiguretheresourceWebTargetwithafilterspecifictotheresource,itwillnotinfluencetheoriginalwebTargetinstance.However,thefilterFilterForExampleComregistrationwillstillbeinheritedbytheresourceWebTargetasithasbeencreatedfromwebTarget.Thismechanismallowsyoutosharethecommonconfigurationofrelatedresources(typicallyhostedunderthesameURIroot,inourcaserepresentedbythewebTargetinstance),whileallowingforfurtherconfigurationspecializationbasedonthespecificrequirementsofeachindividualresource.Thesameconfigurationprinciplesofinheritance(toallowcommonconfigpropagation)anddecoupling(toallowindividualconfigcustomization)appliestoallcomponentsinJAXRSClientAPIdiscussedbelow.
Let'ssaythereisasubresourceonthepath"http://example.com/rest/resource/helloworld".YoucanderiveaWebTargetforthisresourcesimplyby:
Let'sassumethatthehelloworldresourceacceptsaqueryparamforGETrequestswhichdefinesthegreetingmessage.ThenextcodesnippetshowsacodethatcreatesanewWebTargetwiththequeryparamdefined.
PleasenotethatapartfrommethodsthatcanderivenewWebTargetinstancebasedonaURIpathorqueryparameters,theJAXRSWebTargetAPI
1234
ClientConfigclientConfig=newClientConfig()clientConfig.register(MyClientResponseFilter.class)clientConfig.register(newAnotherClientFilter())Clientclient=ClientBuilder.newClient(clientConfig)
123
Clientclient=ClientBuilder.newClient(newClientConfig().register(MyClientResponseFilter.class).register(newAnotherClientFilter())
1 client.register(ThirdClientFilter.class)
123
client.register(FilterA.class).register(newFilterB()).property("myproperty",true)
123456
ClientConfigclientConfig=newClientConfig()clientConfig.register(MyClientResponseFilter.class)clientConfig.register(newAnotherClientFilter())Clientclient=ClientBuilder.newClient(clientConfig)client.register(ThirdClientFilter.class)ConfigurationnewConfiguration=client.getConfiguration()
1 WebTargetwebTarget=client.target("http://example.com/rest")
12
WebTargetwebTarget=client.target("http://example.com/rest")webTarget.register(FilterForExampleCom.class)
1 WebTargetresourceWebTarget=webTarget.path("resource")
1 WebTargethelloworldWebTarget=resourceWebTarget.path("helloworld")
12
WebTargethelloworldWebTargetWithQueryParam=helloworldWebTarget.queryParam("greeting","HiWorld!")
-
containsalsomethodsforworkingwithmatrixparameterstoo.
5.3.5.InvokingaHTTPrequest
Let'snowfocusoninvokingaGETHTTPrequestonthecreatedwebtargets.TostartbuildinganewHTTPrequestinvocation,weneedtocreateanewInvocation.Builder.
Anewinvocationbuilderinstanceiscreatedusingoneoftherequest(...)methodsthatareavailableonWebTarget.Acoupleofthesemethodsacceptparametersthatletyoudefinethemediatypeoftherepresentationrequestedtobereturnedfromtheresource.Herewearesayingthatwerequesta"text/plain"type.ThistellsJerseytoaddaAccept:text/plainHTTPheadertoourrequest.
TheinvocationBuilderisusedtosetuprequestspecificparameters.Herewecansetupheadersfortherequestorforexamplecookieparameters.Inourexamplewesetupa"someheader"headertovaluetrue.
Oncefinishedwithrequestcustomizations,it'stimetoinvoketherequest.Wehavetwooptionsnow.WecanusetheInvocation.BuildertobuildagenericInvocationinstancethatwillbeinvokedsometimelater.UsingInvocationwewillbeabletoe.g.setadditionalrequestpropertieswhicharepropertiesinabatchofseveralrequestsandusethegenericJAXRSInvocationAPItoinvokethebatchofrequestswithoutactuallyknowingallthedetails(suchasrequestHTTPmethod,configurationetc.).Anypropertiessetonaninvocationinstancecanbereadduringtherequestprocessing.Forexample,inacustomClientRequestFilteryoucancallgetProperty()methodonthesuppliedClientRequestContexttoreadarequestproperty.NotethattheserequestpropertiesaredifferentfromtheconfigurationpropertiessetonConfigurable.Asmentionedearlier,anInvocationinstanceprovidesgenericinvocationAPItoinvoketheHTTPrequestitrepresentseithersynchronouslyorasynchronously.SeetheChapter10,AsynchronousServicesandClientsformoreinformationonasynchronousinvocations.
IncaseyoudonotwanttodoanybatchprocessingonyourHTTPrequestinvocationspriortoinvokingthem,thereisanother,moreconvenientapproachthatyoucanusetoinvokeyourrequestsdirectlyfromanInvocation.Builderinstance.ThisapproachisdemonstratedinthenextJavacodelisting.
Whileshort,thecodeintheexampleperformsmultipleactions.First,itwillbuildthetherequestfromtheinvocationBuilder.TheURIofrequestwillbehttp://example.com/rest/resource/helloworld?greeting="Hi%20World!"andthere