45.2. Basic JAX-RS annotations
Overview
The most basic pieces of information required by a RESTful Web service implementation are:
- the URI of the service's resources
- how the class' methods are mapped to the HTTP verbs
JAX-RS defines a set of annotations that provide this basic information. All resource classes must have at least one of these annotations.
Setting the path
The
@Path
annotation specifies the URI of a resource. The annotation is defined by the javax.ws.rs.Path
interface and it can be used to decorate either a resource class or a resource method. It takes a string value as its only parameter. The string value is a URI template that specifies the location of an implemented resource.
The URI template specifies a relative location for the resource. As shown in Example 45.2, “URI template syntax”, the template can contain the following:
- unprocessed path components
- parameter identifiers surrounded by
{
}
NoteParameter identifiers can include regular expressions to alter the default path processing.
Example 45.2. URI template syntax
@Path("resourceName/{param1}/../{paramN}")
For example, the URI template widgets/{color}/{number} would map to widgets/blue/12. The value of the
color
parameter is assigned to blue. The value of the number
parameter is assigned 12.
How the URI template is mapped to a complete URI depends on what the
@Path
annotation is decorating. If it is placed on a root resource class, the URI template is the root URI of all resources in the tree and it is appended directly to the URI at which the service is published. If the annotation decorates a sub-resource, it is relative to the root resource URI.
Specifying HTTP verbs
JAX-RS uses five annotations for specifying the HTTP verb that will be used for a method:
javax.ws.rs.DELETE
specifies that the method maps to aDELETE
.javax.ws.rs.GET
specifies that the method maps to aGET
.javax.ws.rs.POST
specifies that the method maps to aPOST
.javax.ws.rs.PUT
specifies that the method maps to aPUT
.javax.ws.rs.HEAD
specifies that the method maps to aHEAD
.
When you map your methods to HTTP verbs, you must ensure that the mapping makes sense. For example, if you map a method that is intended to submit a purchase order, you would map it to a
PUT
or a POST
. Mapping it to a GET
or a DELETE
would result in unpredictable behavior.