Developing And Securing RESTful Web Services For Oracle WebLogic Server

Transcription

Oracle Fusion MiddlewareDeveloping and Securing RESTful WebServices for Oracle WebLogic Server12c (12.2.1.3.0)E80428-02April 2018

Oracle Fusion Middleware Developing and Securing RESTful Web Services for Oracle WebLogic Server, 12c(12.2.1.3.0)E80428-02Copyright 2013, 2018, Oracle and/or its affiliates. All rights reserved.This software and related documentation are provided under a license agreement containing restrictions onuse and disclosure and are protected by intellectual property laws. Except as expressly permitted in yourlicense agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify,license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means.Reverse engineering, disassembly, or decompilation of this software, unless required by law forinteroperability, is prohibited.The information contained herein is subject to change without notice and is not warranted to be error-free. Ifyou find any errors, please report them to us in writing.If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it onbehalf of the U.S. Government, then the following notice is applicable:U.S. GOVERNMENT END USERS: Oracle programs, including any operating system, integrated software,any programs installed on the hardware, and/or documentation, delivered to U.S. Government end users are"commercial computer software" pursuant to the applicable Federal Acquisition Regulation and agencyspecific supplemental regulations. As such, use, duplication, disclosure, modification, and adaptation of theprograms, including any operating system, integrated software, any programs installed on the hardware,and/or documentation, shall be subject to license terms and license restrictions applicable to the programs.No other rights are granted to the U.S. Government.This software or hardware is developed for general use in a variety of information management applications.It is not developed or intended for use in any inherently dangerous applications, including applications thatmay create a risk of personal injury. If you use this software or hardware in dangerous applications, then youshall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure itssafe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of thissoftware or hardware in dangerous applications.Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks oftheir respective owners.Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks areused under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Opteron,the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced MicroDevices. UNIX is a registered trademark of The Open Group.This software or hardware and documentation may provide access to or information about content, products,and services from third parties. Oracle Corporation and its affiliates are not responsible for and expresslydisclaim all warranties of any kind with respect to third-party content, products, and services unless otherwiseset forth in an applicable agreement between you and Oracle. Oracle Corporation and its affiliates will not beresponsible for any loss, costs, or damages incurred due to your access to or use of third-party content,products, or services, except as set forth in an applicable agreement between you and Oracle.

ContentsPrefaceDocumentation AccessibilityviiConventionsviiWhat’s New in This Guide12New and Changed Features for Release 12c (12.2.1.x)viiiNew and Changed Features for Release 12c (12.2.1)viiiNew and Changed Features for Release 12c (12.1.3)ixNew and Changed Features for Release 12c (12.1.2)ixIntroduction to RESTful Web Services1.1Introduction to the REST Architectural Style1-11.2What are RESTful Web Services?1-21.3Standards Supported for RESTful Web Service Development on WebLogicServer1-21.4Roadmap for Implementing RESTful Web Services1-31.5Learn More About RESTful Web Services1-4Developing RESTful Web Services2.1About RESTful Web Service Development2-12.1.1Summary of Tasks to Develop RESTful Web Services2-22.1.2Example of a RESTful Web Service2-32.2Defining the Root Resource Class2-32.3Defining the Relative URI of the Root Resource and Subresources2-32.42.3.1How to Define the Relative URI of the Resource Class (@Path)2-42.3.2How to Define the Relative URI of Subresources (@Path)2-52.3.3What Happens at Runtime: How the Base URI is Constructed2-5Mapping Incoming HTTP Requests to Java Methods2-62.4.1About the Jersey Bookmark Sample2-72.4.2How to Transmit a Representation of the Resource (@GET)2-8iii

2.4.3How to Create or Update the Representation of the Resource (@PUT)2.4.4How to Delete a Representation of the Resource (@DELETE)2-102.4.5How to Create, Update, or Perform an Action on a Representation of theResource (@POST)2-102.5Customizing Media Types for the Request and Response Messages2.5.12.5.22.5.32.6342-11How To Customize Media Types for the Request Message(@Consumes)2-11How To Customize Media Types for the Response Message(@Produces)2-12What Happens At Runtime: How the Resource Method Is Selected forResponse Messages2-13Extracting Information From the Request Message2.6.12-92-13How to Extract Variable Information from the Request URI(@PathParam)2-142.6.2How to Extract Request Parameters (@QueryParam)2-142.6.3How to Define the DefaultValue (@DefaultValue)2-152.6.4Enabling the Encoding Parameter Values (@Encoded)2-152.7Building Custom Response Messages2-162.8Mapping HTTP Request and Response Entity Bodies Using Entity Providers2-192.9Accessing the Application Context2-202.10Building URIs2-212.11Using Conditional GETs2-222.12Accessing the WADL2-232.13More Advanced RESTful Web Service Tasks2-23Developing RESTful Web Service Clients3.1Summary of Tasks to Develop RESTful Web Service Clients3-13.2Example of a RESTful Web Service Client3-23.3Invoking a RESTful Web Service from a Standalone Client3-2Building, Packaging, and Deploying RESTful Web ServiceApplications4.1Building RESTful Web Service Applications4-14.2Packaging RESTful Web Service Applications4-14.2.1Packaging With an Application Subclass4-24.2.2Packaging With a Servlet4-24.2.2.14.2.2.24.2.3How to Package the RESTful Web Service Application withServlet 3.04-3How to Package the RESTful Web Service Application withPre-3.0 Servlets4-5Packaging as a Default Resource4-6iv

4.35Deploying RESTful Web Service ApplicationsSecuring RESTful Web Services and Clients5.1About RESTful Web Service Security5-15.2Securing RESTful Web Services and Clients Using OWSM Policies5-15.3Securing RESTful Web Services Using web.xml5-25.4Securing RESTful Web Services Using SecurityContext5-35.5Securing RESTful Web Services Using Java Security Annotations5-46Testing RESTful Web Services7Monitoring RESTful Web Services and Clients7.1About Monitoring RESTful Web Services7-17.2Monitoring RESTful Web Services Using Enterprise Manager FusionMiddleware Control7-27.3Monitoring RESTful Web Services Using the Administration Console7-27.4Monitoring RESTful Web Services Using WLST7-27.5Enabling the Tracing Feature7-67.6Disabling RESTful Web Service Application Monitoring7-67.6.1Disabling Monitoring for a RESTful Web Service Application UsingJersey Property7-7Disabling Monitoring for a RESTful Web Service Application UsingWebLogic Configuration MBean7-8Disabling RESTful Web Service Application Monitoring for a WebLogicDomain7-9Enable Monitoring of Synthetic Jersey Resources in a RESTful Web ServiceApplication7-107.6.27.6.37.78A4-7Using Server-Sent Events in WebLogic Server8.1Overview of Server-Sent Events (SSE)8-18.2Understanding the WebLogic Server-Sent Events API8-18.3Sample Applications for Server-Sent Events8-2Compatibility with Earlier Jersey/JAX-RS ReleasesA.1Develop RESTful Web Service Clients Using Jersey 1.18 (JAX-RS 1.1 RI)A-1A.1.1Example of a RESTful Web Service ClientA-2A.1.2Creating and Configuring a Client InstanceA-2A.1.3Creating a Web Resource InstanceA-4v

A.1.4A-5A.1.4.1How to Build RequestsA-5A.1.4.2How to Send HTTP RequestsA-6A.1.4.3How to Pass Query ParametersA-7A.1.4.4How to Configure the Accept HeaderA-7A.1.4.5How to Add a Custom HeaderA-8A.1.4.6How to Configure the Request EntityA-8A.1.5Receiving a Response from a ResourceA-9A.1.5.1How to Access the Status of RequestA-9A.1.5.2How to Get the Response EntityA-9A.1.6A.2Sending Requests to the ResourceMore Advanced RESTful Web Service Client TasksSupport for Jersey 1.18 (JAX-RS 1.1 RI) Deployments Packaged with Pre-3.0ServletsA-9A-10vi

PrefaceThis preface describes the document accessibility features and conventions used inthis guide— Developing and Securing RESTful Web Services for Oracle WebLogicServer.Documentation AccessibilityFor information about Oracle's commitment to accessibility, visit the OracleAccessibility Program website at http://www.oracle.com/pls/topic/lookup?ctx acc&id docacc.Access to Oracle SupportOracle customers that have purchased support have access to electronic supportthrough My Oracle Support. For information, visit http://www.oracle.com/pls/topic/lookup?ctx acc&id info or visit http://www.oracle.com/pls/topic/lookup?ctx acc&id trsif you are hearing impaired.ConventionsThe following text conventions are used in this document:ConventionMeaningboldfaceBoldface type indicates graphical user interface elements associatedwith an action, or terms defined in text or the glossary.italicItalic type indicates book titles, emphasis, or placeholder variables forwhich you supply particular values.monospaceMonospace type indicates commands within a paragraph, URLs, codein examples, text that appears on the screen, or text that you enter.vii

What’s New in This GuideWhat’s New in This GuideLearn about the new and changed features of RESTful web services and get links toadditional information. This document was released initially in Oracle FusionMiddleware 12c Release 1 (12.1.1).New and Changed Features for Release 12c (12.2.1.x)There are no updates to this guide for the Oracle Fusion Middleware 12c (12.2.1.x)release.For a comprehensive listing of the new WebLogic Server features introduced in thisrelease, see What's New in Oracle WebLogic Server.New and Changed Features for Release 12c (12.2.1)For the Oracle Fusion Middleware Release 12c (12.2.1) release, RESTful webservices includes several new and changed features that are described in thisdocument. These include the following: Provides support for Jersey 2.x (JAX-RS 2.0 RI) by default in this release.Registration as a shared library with WebLogic Server is no longer required. Provides enhanced monitoring of RESTful web services in the WebLogicAdministration Console, including enhanced runtime statistics for your RESTfulapplications and resources, detailed deployment and configuration data, globalexecution statistics, and resource and resource method execution statistics. SeeMonitoring RESTful Web Services and Clients. Includes the ability to disable RESTful web services monitoring at the individualapplication level, or globally at the domain level. See Disabling RESTful WebService Application Monitoring. Reflects support for the Jersey 2.21.1 JAX-RS 2.0 RI. Supports securing Jersey 2.x (JAX-RS 2.0 RI) web services using Oracle WebServices Manager (OWSM) security policies. See Securing RESTful Web Servicesand Clients Using OWSM Policies. Adds support for Java EE 7. The Jersey 1.x client API is deprecated. It is recommended that you update yourRESTful client applications to use the JAX-RS 2.0 client APIs at your earliestconvenience. Removes support for the Jersey 1.x (JAX-RS 1.1. RI) server APIs. You should usethe corresponding standard JAX-RS 2.0 or Jersey 2.x APIs instead.viii

What’s New in This GuideNote:Support for the Jersey 1.18 (JAX-RS 1.1RI) client APIs are deprecated inthis release of WebLogic Server but are maintained for backwardcompatibility. See Develop RESTful Web Service Clients Using Jersey1.18 (JAX-RS 1.1 RI).Oracle recommends that you update your RESTful client applications touse the JAX-RS 2.0 client APIs at your earliest convenience.New and Changed Features for Release 12c (12.1.3)Oracle Fusion Middleware Release 12c (12.1.3) includes two new and changedfeatures for RESTful web services that are described in this document. Reflects support of the Jersey 2.5.1 Java API for RESTful Web Services (JAX-RS)2.0 Reference Implementation (RI) as a pre-built shared library. Reflects support for the Jersey 1.18 JAX-RS 1.1. RI.New and Changed Features for Release 12c (12.1.2)Oracle Fusion Middleware 12c (12.1.2) includes two new and changed features forRESTful web services that are described in this document. Secure RESTful web services using Oracle Web Services Manager (OWSM)policies. See Securing RESTful Web Services and Clients Using OWSM Policies. New standalone web service client JAR files that support basic RESTful webservice client-side functionality and Oracle Web Services Manager (OWSM)security policy support. See Invoking a RESTful Web Service from a StandaloneClient.ix

1Introduction to RESTful Web ServicesRESTful web services are Java EE web services that you develop to conform to theRepresentational State Transfer (REST) architectural style using Java API for RESTfulWeb Services (JAX-RS). Introduction to the REST Architectural Style What are RESTful Web Services? Standards Supported for RESTful Web Service Development on WebLogic Server Roadmap for Implementing RESTful Web Services Learn More About RESTful Web Services1.1 Introduction to the REST Architectural StyleREST describes any simple interface that transmits data over a standardized interface(such as HTTP) without an additional messaging layer, such as Simple Object AccessProtocol (SOAP). REST is an architectural style—not a toolkit—that provides a set ofdesign rules for creating stateless services that are viewed as resources, or sources ofspecific information (data and functionality). Each resource can be identified by itsunique Uniform Resource Identifiers (URIs).A client accesses a resource using the URI and a standardized fixed set of methods,and a representation of the resource is returned. A representation of a resource istypically a document that captures the current or intended state of a resource. Theclient is said to transfer state with each new resource representation.Table 1-1 defines a set of constraints defined by the REST architectural style that mustbe adhered to in order for an application to be considered "RESTful."Table 1-1Constraints of the REST Architectural StyleConstraintDescriptionAddressabilityIdentifies all resources using a uniform resource identifier (URI). In the Englishlanguage, URIs would be the equivalent of a noun.Uniform interfaceEnables the access of a resource using a uniform interface, such as HTTP methods(GET, POST, PUT, and DELETE). Applying the English language analogy, thesemethods would be considered verbs, describing the actions that are applicable to thenamed resource.Client-server architectureSeparates clients and servers into interface requirements and data storagerequirements. This architecture improves portability of the user interface acrossmultiple platforms and scalability by simplifying server components.1-1

Chapter 1What are RESTful Web Services?Table 1-1(Cont.) Constraints of the REST Architectural StyleConstraintDescriptionStateless interactionUses a stateless communication protocol, typically Hypertext Transport Protocol(HTTP). All requests must contain all of the information required for a particularrequest. Session state is stored on the client only.This interactive style improves: Visibility—Single request provides the full details of the request.Reliability—Eases recovery from partial failures.Scalability—Not having to store state enables the server to free resourcesquickly.CacheableEnables the caching of client responses. Responses must be identified as cacheableor non-cacheable. Caching eliminates some interactions, improving efficiency,scalability, and perceived performance.Layered systemEnables client to connect to an intermediary server rather than directly to the endserver (without the client's knowledge). Use of intermediary servers improve systemscalability by offering load balancing and shared caching.1.2 What are RESTful Web Services?RESTful web services are services that are built according to REST principles and, assuch, are designed to work well on the Web.RESTful web services conform to the architectural style constraints defined inTable 1-1. Typically, RESTful web services are built on the HTTP protocol andimplement operations that map to the common HTTP methods, such as GET, POST,PUT, and DELETE to retrieve, create, update, and delete resources, respectively.1.3 Standards Supported for RESTful Web ServiceDevelopment on WebLogic ServerThe JAX-RS provides support for creating web services according to RESTarchitectural style. JAX-RS uses annotations to simplify the development of RESTfulweb services. By simply adding annotations to your web service, you can define theresources and the actions that can be performed on those resources. JAX-RS is partof the Java EE 7 full profile, and is integrated with Contexts and Dependency Injection(CDI) for the Java EE Platform (CDI), Enterprise JavaBeans (EJB) technology, andJava Servlet technology.WebLogic Server supports the following JAX-RS API and Reference Implementation(RI): JAX-RS 2.0 Rev a Jersey 2.22.41-2

Chapter 1Roadmap for Implementing RESTful Web ServicesNote:Jersey 2.x (JAX-RS 2.0 RI) support is provided by default in this release ofWebLogic Server. Registration as a shared library is no longer required.The Jersey 1.x server-side APIs are no longer supported. You should usethe corresponding standard JAX-RS 2.0 or Jersey 2.x APIs instead. TheJersey 1.x client API is deprecated. It is recommended that you update yourRESTful client applications to use the JAX-RS 2.0 client APIs at your earliestconvenience.The Jersey 2.x (JAX-RS 2.0 RI) includes the following functionality: Jersey JAX-RS API JSON processing and streamingTable 1-2 lists key features delivered with Jersey 2.x (JAX-RS 2.0 RI).Table 1-2Key Features in Jersey 2.x (JAX-RS 2.0 RI)Key FeatureDescriptionClient APICommunicate with RESTful web services in a standard way. The Client API facilitatesthe consumption of a web service exposed via HTTP protocol and enables developersto concisely and efficiently implement portable client-side solutions that leverageexisting and well established client-side HTTP connector implementations.For complete details, see: AsynchronouscommunicationClient API in Jersey 2.22 User GuideAccessing REST Resources with the JAX-RS Client API in Java EE 7 TutorialInvoke and process requests asynchronously.For complete details, see: Filters and interceptorsAsynchronous Services and Clients in the Jersey 2.22 User GuideAdvanced Features of the Client API in Java EE 7 TutorialUsing filters, modify inbound and outbound requests and responses., such as headerinformation. Using interceptors, modify entity input and output streams. Filters andinterceptors can be used on both the client and server side.For complete details, see Filters and Interceptors in the Jersey 2.22 User Guide.For more information about JAX-RS and samples, see Learn More About RESTfulWeb Services.1.4 Roadmap for Implementing RESTful Web ServicesReview a roadmap of common tasks for developing, packaging and deploying,securing, and monitoring RESTful web services and clients. These tasks are listed inTable 1-3.1-3

Chapter 1Learn More About RESTful Web ServicesTable 1-3Roadmap for Implementing RESTful Web Services and ClientsTaskMore InformationDevelop RESTful web services.Developing RESTful Web ServicesDevelop clients to invoke the RESTful webservices.Summary of Tasks to Develop RESTful Web Service ClientsPackage and deploy RESTful web services. Packaging With an Application SubclassPackaging With a ServletPackaging as a Default ResourceSecure RESTful web services. Securing RESTful Web Services Using web.xmlSecuring RESTful Web Services Using SecurityContextSecuring RESTful Web Services Using Java SecurityAnnotationsTest RESTful web services.Testing RESTful Web ServicesMonitor RESTful web services.Monitoring RESTful Web Services and Clients(Optional) Migrate existing applications fromJersey 1.x to 2.x.Migration Guide in Jersey 2.22 User Guide1.5 Learn More About RESTful Web ServicesAdditional information about RESTful web services is available from resources such asthe Community Wiki for Project Jersey, jcp.org, the JSR-339 JAX-RS 2.0 Specification,and more. These resources are listed in Table 1-4.Table 1-4Resources for More InformationResourceLinkJersey User GuideJersey 2.22 User GuideJersey API JavadocJersey 2.22 API DocumentationCommunity Wiki for Project https://jersey.github.io/JerseyJSR-339 JAX-RS 2.0Specificationhttps://jcp.org/en/jsr/detail?id 339JAX-RS API a/apidocs/index.htmlJAX-RS Projecthttps://jax-rs-spec.java.net/RESTful Web Services(JAX-RS) sampleSample Application and Code Examples in Understanding Oracle WebLogic Server.The Java EE 7 Tutorial—Building RESTful WebServices With rs.htm"Representational Statehttp://www.ics.uci.edu/ fielding/pubs/dissertation/rest arch style.htmTransfer (REST)" inArchitectural Styles andthe Design of Networkbased SoftwareArchitectures (Dissertationby Roy Fielding)1-4

2Developing RESTful Web ServicesTo develop Java EE web services that conform to the Representational State Transfer(REST) architectural style using Java API for RESTful Web Services (JAX-RS), youperform tasks such as defining the root resource class, mapping incoming HTTPrequests to Java methods, customizing media types for requests and responses, andmore. About RESTful Web Service Development Defining the Root Resource Class Defining the Relative URI of the Root Resource and Subresources Mapping Incoming HTTP Requests to Java Methods Customizing Media Types for the Request and Response Messages Extracting Information From the Request Message Building Custom Response Messages Mapping HTTP Request and Response Entity Bodies Using Entity Providers Accessing the Application Context Building URIs Using Conditional GETs Accessing the WADL More Advanced RESTful Web Service Tasks2.1 About RESTful Web Service DevelopmentJAX-RS is a Java programming language API that uses annotations to simplify thedevelopment of RESTful web services. JAX-RS annotations are runtime annotations.When you deploy the Java EE application archive containing JAX-RS resourceclasses to WebLogic Server, as described in Building, Packaging, and DeployingRESTful Web Service Applications , the runtime configures the resources, generatesthe helper classes and artifacts, and exposes the resource to clients.The following sections provide more information about RESTful web servicedevelopment: Summary of Tasks to Develop RESTful Web Services Example of a RESTful Web ServiceFor information about developing RESTful web services using Oracle JDeveloper, seeCreating RESTful Web Services and Clients in Developing Applications with OracleJDeveloper.2-1

Chapter 2About RESTful Web Service Development2.1.1 Summary of Tasks to Develop RESTful Web ServicesTable 2-1 summarizes a subset of the tasks that are required to develop RESTful webservice using JAX-RS annotations. For more information about advanced tasks, seeMore Advanced RESTful Web Service Tasks.Note:In addition to the development tasks described in Table 2-1, you may wish totake advantage of features available with Jersey 2.x (JAX-RS 2.0 RI) whendeveloping your RESTful web services. For a list of key features, seeTable 1-2.Table 2-1Summary of Tasks to Develop RESTful Web ServicesTaskMore InformationDefine the root resource class.Defining the Root Resource ClassDefine the relative URI of the root resource class and its Defining the Relative URI of the Root Resource andmethods using the @Path annotation.SubresourcesIf you define the @Path annotation using a variable, youcan assign a value to it using the @PathParamannotation.Map incoming HTTP requests to your Java methodsusing @GET, @POST, @PUT, or @DELETE, to get, create,update, or delete representations of the resource,respectively.Mapping Incoming HTTP Requests to Java MethodsCustomize the request and response messages, asrequired, to specify the MIME media types ofrepresentations a resource can produce and consume.Customizing Media Types for the Request andResponse MessagesExtract information from the request.Extracting Information From the Request MessageBuild custom response messages to customizeresponse codes or include additional metadata.Building Custom Response MessagesAccess information about the application deploymentcontext or the context of individual requests.Accessing the Application ContextBuild new or extend existing resource URIs.Building URIsEvaluate one or more preconditions before processing a Using Conditional GETsGET request, potentially reducing bandwidth andimproving server performance.Access the WADL.Accessing the WADLOptionally, create a class that extendsjavax.ws.rs.core.Application to define thecomponents of a RESTful web service applicationdeployment and provides additional metadata.Packaging With an Application SubclassSecure your RESTful web services.Securing RESTful Web Services and Clients2-2

Chapter 2Defining the Root Resource Class2.1.2 Example of a RESTful Web ServiceExample 2-1 provides a simple example of a RESTful web service. In this example: The helloWorld class is a resource with a relative URI path defined as /helloworld.At runtime, if the context root for the WAR file is defined as http://examples.com,the full URI to access the resource is http://examples.com/helloworld. SeeDefining the Relative URI of the Root Resource and Subresources. The sayHello method supports the HTTP GET method. See Mapping IncomingHTTP Requests to Java Methods. The sayHello method produces content of the MIME media type text/plain. SeeCustomizing Media Types for the Request and Response Messages.Additional examples are listed in Learn More About RESTful Web Services.Example 2-1Simple RESTful Web Servicepackage samples.helloworld;import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.Produces;// Specifies the path to the RESTful service@Path("/helloworld")public class helloWorld {// Specifies that the method processes HTTP GET requests@GET@Produces("text/plain")public String sayHello() {return "Hello World!";}}2.2 Defining the Root Resource ClassA root resource class is a Plain Old Java Object (POJO) that meets specific annotationrequirements. The root resource class must satisfy one or both of the followingstatements: Is annotated with @Path. See Defining the Relative URI of the Root Resource andSubresources. Has at least one method annotated with @Path or with a request methoddesignator, such as @GET, @POST, @PUT, or @DELETE. A resource method is a method inthe resource class that is annotated using a request method designator. SeeMapping Incoming HTTP Requests to Java Methods.2.3 Defining the Relative URI of the Root Resource andSubresourcesAdd the javax.ws.rs.Path annotation at the class level of the resource to define therelative URI of the RESTful web service. Such classes are referred to as root resource2-3

Chapter 2Defining the Relative URI of the Root Resource and Subresourcesclasses. You can add @Path on methods of the root resource class as well, to definesubresources to group specific functionality.The following sections describe how to define the relative URI of the root resource andsubresources: How to Define the Relative URI of the Resource Class (@Path) How to Define the Relative URI of Subresources (@Path) What Happens at Runtime: How the Base URI is Constructed2.3.1 How to Define the Relative URI of the Resource Class (@Path)The @Path annotation defines the relative URI path for the resource, and can bedefined as a constant or variable value (referred to as "URI path template"). You canadd the @Path annotation at the class or method level.To define the URI as a constant value, pass a constant value to the @Path annotation.Preceding and ending slashes (/) are optional.In Example 2-2, the relative URI for the resource class is defined as the constantvalue, /helloworld.Example 2-2Defining the Relative URI as a Constant Valuepackage samples.helloworld;import javax.ws.rs.Path;.// Specifies the path to the RESTful service@Path("/helloworld")public class helloWorld {. . .}To define the URI as a URI path template, pass one or more variable values enclosedin braces in the @Path annotation. Then, you can use the javax.ws.rs.PathParamannotation to extract variable information from the request URI, defined by the @Pathannotation, and initialize the value of the method parameter, as described in How toExtract Variable Information from the Request URI (@PathParam).In Example 2-3, the relative URI for the resource class is defined using a variable,enclosed in braces, for example, /users/{username}.Example 2-3Defining the Relative URI as a Variable Valuepackage samples.helloworld;import javax.ws.rs.Path;.// Specifies the path to the RESTful service@Path("/users/{username}")public class helloWorld {. . .}}To further customize the variable, you can override the default regular expression of"[ /] ?" by specifying the expected regular expression as part of the variable definition.For example:@Path("users/{username: [a-zA-Z][a-zA-Z 0-9]}")In this example, the username variable will match only user names that begin with oneuppercase or lowercase letter followed by zero or more alphanumeric characters or2-4

Cha

1.4 Roadmap for Implementing RESTful Web Services 1-3 1.5 Learn More About RESTful Web Services 1-4 2 Developing RESTful Web Services 2.1 About RESTful Web Service Development 2-1 2.1.1 Summary of Tasks to Develop RESTful Web Services 2-2 2.1.2 Example of a RESTful Web Service 2-3 2.2 Defining the Root Resource Class 2-3