Jersey RESTFul Services : Overview de JAX-RS 1.1

Chapter 2. Overview of JAX-RS 1.1

This chapter presents an overview of the JAX-RS 1.1 features.

The JAX-RS 1.1 API may be found online here.

The JAX-RS 1.1 specification draft may be found online here.

2.1. Root Resource Classes

Root resource classes are POJOs (Plain Old Java Objects) that are annotated with @Path have at least one method annotated with @Path or a resource method designator annotation such as @GET@PUT@POST@DELETE. Resource methods are methods of a resource class annotated with a resource method designator. This section shows how to use Jersey to annotate Java objects to create RESTful web services.

The following code example is a very simple example of a root resource class using JAX-RS annotations. The example code shown here is from one of the samples that ships with Jersey, the zip file of which can be found in the maven repository here.

Example 2.1. Simple hello world root resource class 

  1 package;
  3 import;
  4 import;
  5 import;
  7 // The Java class will be hosted at the URI path "/helloworld"
  8 @Path("/helloworld")
  9 public class HelloWorldResource {
 11     // The Java method will process HTTP GET requests
 12     @GET
 13     // The Java method will produce content identified by the MIME Media
 14     // type "text/plain"
 15     @Produces("text/plain")
 16     public String getClichedMessage() {
 17         // Return some cliched textual content
 18         return "Hello World";
 19     }
 20 }

Let’s look at some of the JAX-RS annotations used in this example.

2.1.1. @Path

The @Path annotation’s value is a relative URI path. In the example above, the Java class will be hosted at the URI path /helloworld. This is an extremely simple use of the @Path annotation. What makes JAX-RS so useful is that you can embed variables in the URIs.

URI path templates are URIs with variables embedded within the URI syntax. These variables are substituted at runtime in order for a resource to respond to a request based on the substituted URI. Variables are denoted by curly braces. For example, look at the following @Path annotation:


In this type of example, a user will be prompted to enter their name, and then a Jersey web service configured to respond to requests to this URI path template will respond. For example, if the user entered their username as “Galileo”, the web service will respond to the following URL:

To obtain the value of the username variable the @PathParam may be used on method parameter of a request method, for example:

Example 2.2. Specifying URI path parameter 

  1 @Path("/users/{username}")
  2 public class UserResource {
  4     @GET
  5     @Produces("text/xml")
  6     public String getUser(@PathParam("username") String userName) {
  7         ...
  8     }
  9 }

If it is required that a user name must only consist of lower and upper case numeric characters then it is possible to declare a particular regular expression, which overrides the default regular expression, “[^/]+?”, for example:

@Path("users/{username: [a-zA-Z][a-zA-Z_0-9]*}")

In this type of example the username variable will only match user names that begin with one upper or lower case letter and zero or more alpha numeric characters and the underscore character. If a user name does not match that a 404 (Not Found) response will occur.

@Path value may or may not begin with a ‘/’, it makes no difference. Likewise, by default, a @Path value may or may not end in a ‘/’, it makes no difference, and thus request URLs that end or do not end in a ‘/’ will both be matched. However, Jersey has a redirection mechanism, which if enabled, automatically performs redirection to a request URL ending in a ‘/’ if a request URL does not end in a ‘/’ and the matching @Path does end in a ‘/’.

2.1.2. HTTP Methods

@GET@PUT@POST@DELETE and @HEAD are resource method designator annotations defined by JAX-RS and which correspond to the similarly named HTTP methods. In the example above, the annotated Java method will process HTTP GET requests. The behavior of a resource is determined by which of the HTTP methods the resource is responding to.

The following example is an extract from the storage service sample that shows the use of the PUT method to create or update a storage container:

Example 2.3. PUT method 

  1 @PUT
  2 public Response putContainer() {
  3     System.out.println("PUT CONTAINER " + container);
  5     URI uri =  uriInfo.getAbsolutePath();
  6     Container c = new Container(container, uri.toString());
  8     Response r;
  9     if (!MemoryStore.MS.hasContainer(c)) {
 10         r = Response.created(uri).build();
 11     } else {
 12         r = Response.noContent().build();
 13     }
 15     MemoryStore.MS.createContainer(c);
 16     return r;
 17 }

By default the JAX-RS runtime will automatically support the methods HEAD and OPTIONS, if not explicitly implemented. For HEAD the runtime will invoke the implemented GET method (if present) and ignore the response entity (if set). For OPTIONS the Allow response header will be set to the set of HTTP methods support by the resource. In addition Jersey will return a WADL document describing the resource.

2.1.3. @Produces

The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client. In this example, the Java method will produce representations identified by the MIME media type “text/plain”.

@Produces can be applied at both the class and method levels. Here’s an example:

Example 2.4. Specifying output MIME type 

  1 @Path("/myResource")
  2 @Produces("text/plain")
  3 public class SomeResource {
  4     @GET
  5     public String doGetAsPlainText() {
  6         ...
  7     }
  9     @GET
 10     @Produces("text/html")
 11     public String doGetAsHtml() {
 12         ...
 13     }
 14 }

The doGetAsPlainText method defaults to the MIME type of the @Produces annotation at the class level. The doGetAsHtml method’s @Produces annotation overrides the class-level @Produces setting, and specifies that the method can produce HTML rather than plain text.

If a resource class is capable of producing more that one MIME media type then the resource method chosen will correspond to the most acceptable media type as declared by the client. More specifically the Accept header of the HTTP request declared what is most acceptable. For example if the Accept header is:

Accept: text/plain

then the doGetAsPlainText method will be invoked. Alternatively if the Accept header is:

Accept: text/plain;q=0.9, text/html

which declares that the client can accept media types of “text/plain” and “text/html” but prefers the latter, then the doGetAsHtml method will be invoked.

More than one media type may be declared in the same @Produces declaration, for example:

Example 2.5. Using multiple output MIME types 

  1 @GET
  2 @Produces({"application/xml", "application/json"})
  3 public String doGetAsXmlOrJson() {
  4     ...
  5 }

The doGetAsXmlOrJson method will get invoked if either of the media types “application/xml” and “application/json” are acceptable. If both are equally acceptable then the former will be chosen because it occurs first.

The examples above refer explicitly to MIME media types for clarity. It is possible to refer to constant values, which may reduce typographical errors, see the constant field values of MediaType.

2.1.4. @Consumes

The @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client. The above example can be modified to set the cliched message as follows:

Example 2.6. Specifying input MIME type 

  1 @POST
  2 @Consumes("text/plain")
  3 public void postClichedMessage(String message) {
  4     // Store the message
  5 }

In this example, the Java method will consume representations identified by the MIME media type “text/plain”. Notice that the resource method returns void. This means no representation is returned and response with a status code of 204 (No Content) will be returned.

@Consumes can be applied at both the class and method levels and more than one media type may be declared in the same @Consumes declaration.

2.2. Deploying a RESTful Web Service

JAX-RS provides a deployment agnostic abstract class Application for declaring root resource and provider classes, and root resource and provider singleton instances. A Web service may extend this class to declare root resource and provider classes. For example,

Example 2.7. Deployment agnostic application model 

  1 public class MyApplication extends Application {
  2     public Set<Class<?>> getClasses() {
  3         Set<Class<?>> s = new HashSet<Class<?>>();
  4         s.add(HelloWorldResource.class);
  5         return s;
  6     }
  7 }

Alternatively it is possible to reuse one of Jersey’s implementations that scans for root resource and provider classes given a classpath or a set of package names. Such classes are automatically added to the set of classes that are returned by getClasses. For example, the following scans for root resource and provider classes in packages “”, “” and in any sub-packages of those two:

Example 2.8. Reusing Jersey implementation in your custom application model 

  1 public class MyApplication extends PackagesResourceConfig {
  2     public MyApplication() {
  3         super(";");
  4     }
  5 }

There are multiple deployment options for the class that implements Application interface in the Servlet 3.0 container. For simple deployments, no web.xml is needed at all. Instead, an @ApplicationPath annotation can be used to annotate the user defined application class and specify the the base resource URI of all application resources:

Example 2.9. Deployment of a JAX-RS application using @ApplicationPath with Servlet 3.0 

  1 @ApplicationPath("resources")
  2 public class MyApplication extends PackagesResourceConfig {
  3     public MyApplication() {
  4         super(";");
  5     }
  6     ...
  7 }

You also need to set maven-war-plugin attribute failOnMissingWebXml to false in pom.xml when building .war without web.xml file using maven:

Example 2.10. Configuration of maven-war-plugin in pom.xml with Servlet 3.0 

  1 <plugins>
  2  ...
  3  <plugin>
  4    <groupId>org.apache.maven.plugins</groupId>
  5    <artifactId>maven-war-plugin</artifactId>
  6    <version>2.1.1</version>
  7    <configuration>
  8        <failOnMissingWebXml>false</failOnMissingWebXml>
  9    </configuration>
 10    </plugin>
 11  ...
 12  </plugins>

Another deployment option is to declare JAX-RS application details in the web.xml. This is usually suitable in case of more complex deployments, e.g. when security model needs to be properly defined or when additional initialization parameters have to be passed to Jersey runtime. JAX-RS 1.1 specifies that a fully qualified name of the class that implements Application may be declared in the <servlet-name> element of the JAX-RS application’s web.xml. This is supported in a Web container implementing Servlet 3.0 as follows:

Example 2.11. Deployment of a JAX-RS application using web.xml with Servlet 3.0 

  1 <web-app>
  2     <servlet>
  3         <servlet-name></servlet-name>
  4     </servlet>
  5     ...
  6     <servlet-mapping>
  7         <servlet-name></servlet-name>
  8         <url-pattern>/resources</url-pattern>
  9     </servlet-mapping>
 10     ...
 11 </web-app>

Note that the <servlet-class> element is omitted from the servlet declaration. This is a correct declaration utilizing the Servlet 3.0 extension mechanism. Also note that <servlet-mapping> is used to define the base resource URI.

When running in a Servlet 2.x then instead it is necessary to declare the Jersey specific servlet and pass the Application implementation class name as one of the servlet’s init-param entries:

Example 2.12. Deployment of your application using Jersey specific servlet 

  1 <web-app>
  2     <servlet>
  3         <servlet-name>Jersey Web Application</servlet-name>
  4         <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  5         <init-param>
  6             <param-name></param-name>
  7             <param-value></param-value>
  8         </init-param>
  9         ...
 10     </servlet>
 11     ...
 12 </web-app>

Alternatively a simpler approach is to let Jersey choose the PackagesResourceConfig implementation automatically by declaring the packages as follows:

Example 2.13. Using Jersey specific servlet without an application model instance 

  1 <web-app>
  2     <servlet>
  3         <servlet-name>Jersey Web Application</servlet-name>
  4         <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  5         <init-param>
  6             <param-name></param-name>
  7             <param-value>;</param-value>
  8         </init-param>
  9         ...
 10     </servlet>
 11     ...
 12 </web-app>

JAX-RS also provides the ability to obtain a container specific artifact from an Application instance. For example, Jersey supports using Grizzly as follows:

SelectorThread st = RuntimeDelegate.createEndpoint(new MyApplication(), SelectorThread.class);

Jersey also provides Grizzly helper classes to deploy the ServletThread instance at a base URL for in-process deployment.

The Jersey samples provide many examples of Servlet-based and Grizzly-in-process-based deployments.

2.3. Extracting Request Parameters

Parameters of a resource method may be annotated with parameter-based annotations to extract information from a request. A previous example presented the use @PathParam to extract a path parameter from the path component of the request URL that matched the path declared in @Path.

@QueryParam is used to extract query parameters from the Query component of the request URL. The following example is an extract from the sparklines sample:

Example 2.14. Query parameters 

  1 @Path("smooth")
  2 @GET
  3 public Response smooth(
  4         @DefaultValue("2") @QueryParam("step") int step,
  5         @DefaultValue("true") @QueryParam("min-m") boolean hasMin,
  6         @DefaultValue("true") @QueryParam("max-m") boolean hasMax,
  7         @DefaultValue("true") @QueryParam("last-m") boolean hasLast,
  8         @DefaultValue("blue") @QueryParam("min-color") ColorParam minColor,
  9         @DefaultValue("green") @QueryParam("max-color") ColorParam maxColor,
 10         @DefaultValue("red") @QueryParam("last-color") ColorParam lastColor
 11         ) { ... }

If a query parameter “step” exists in the query component of the request URI then the “step” value will be will extracted and parsed as a 32 bit signed integer and assigned to the step method parameter. If “step” does not exist then a default value of 2, as declared in the @DefaultValue annotation, will be assigned to the step method parameter. If the “step” value cannot be parsed as a 32 bit signed integer then a HTTP 404 (Not Found) response is returned. User defined Java types such as ColorParam may be used, which as implemented as follows:

Example 2.15. Custom Java type for consuming request parameters 

  1 public class ColorParam extends Color {
  2     public ColorParam(String s) {
  3         super(getRGB(s));
  4     }
  6     private static int getRGB(String s) {
  7         if (s.charAt(0) == '#') {
  8             try {
  9                 Color c = Color.decode("0x" + s.substring(1));
 10                 return c.getRGB();
 11             } catch (NumberFormatException e) {
 12                 throw new WebApplicationException(400);
 13             }
 14         } else {
 15             try {
 16                 Field f = Color.class.getField(s);
 17                 return ((Color)f.get(null)).getRGB();
 18             } catch (Exception e) {
 19                 throw new WebApplicationException(400);
 20             }
 21         }
 22     }
 23 }

In general the Java type of the method parameter may:

  1. Be a primitive type;
  2. Have a constructor that accepts a single String argument;
  3. Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String) and java.util.UUID.fromString(String)); or
  4. Be List<T>Set<T> or SortedSet<T>, where T satisfies 2 or 3 above. The resulting collection is read-only.

Sometimes parameters may contain more than one value for the same name. If this is the case then types in 4) may be used to obtain all values.

If the @DefaultValue is not used in conjunction with @QueryParam and the query parameter is not present in the request then value will be an empty collection for ListSet or SortedSetnull for other object types, and the Java-defined default for primitive types.

The @PathParam and the other parameter-based annotations, @MatrixParam@HeaderParam@CookieParam@FormParam obey the same rules as @QueryParam@MatrixParam extracts information from URL path segments. @HeaderParam extracts information from the HTTP headers. @CookieParam extracts information from the cookies declared in cookie related HTTP headers.

@FormParam is slightly special because it extracts information from a request representation that is of the MIME media type "application/x-www-form-urlencoded" and conforms to the encoding specified by HTML forms, as described here. This parameter is very useful for extracting information that is POSTed by HTML forms, for example the following extracts the form parameter named “name” from the POSTed form data:

Example 2.16. Processing POSTed HTML form 

  1 @POST
  2 @Consumes("application/x-www-form-urlencoded")
  3 public void post(@FormParam("name") String name) {
  4     // Store the message
  5 }

If it is necessary to obtain a general map of parameter name to values then, for query and path parameters it is possible to do the following:

Example 2.17. Obtaining general map of URI path and/or query parameters 

  1 @GET
  2 public String get(@Context UriInfo ui) {
  3     MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
  4     MultivaluedMap<String, String> pathParams = ui.getPathParameters();
  5 }

For header and cookie parameters the following:

Example 2.18. Obtaining general map of header parameters 

  1 @GET
  2 public String get(@Context HttpHeaders hh) {
  3     MultivaluedMap<String, String> headerParams = hh.getRequestHeaders();
  4     Map<String, Cookie> pathParams = hh.getCookies();
  5 }

In general @Context can be used to obtain contextual Java types related to the request or response. For form parameters it is possible to do the following:

Example 2.19. Obtaining general map of form parameters 

  1 @POST
  2 @Consumes("application/x-www-form-urlencoded")
  3 public void post(MultivaluedMap<String, String> formParams) {
  4     // Store the message
  5 }

2.4. Representations and Java Types

Previous sections on @Produces and @Consumes referred to MIME media types of representations and showed resource methods that consume and produce the Java type String for a number of different media types. However, String is just one of many Java types that are required to be supported by JAX-RS implementations.

Java types such as byte[] and are supported. In addition JAXB beans are supported. Such beans are JAXBElement or classes annotated with @XmlRootElement or @XmlType. The samples jaxb and json-from-jaxb show the use of JAXB beans.

Unlike method parameters that are associated with the extraction of request parameters, the method parameter associated with the representation being consumed does not require annotating. A maximum of one such unannotated method parameter may exist since there may only be a maximum of one such representation sent in a request.

The representation being produced corresponds to what is returned by the resource method. For example JAX-RS makes it simple to produce images that are instance of File as follows:

Example 2.20. Using File with a specific MIME type to produce a response 

  1 @GET
  2 @Path("/images/{image}")
  3 @Produces("image/*")
  4 public Response getImage(@PathParam("image") String image) {
  5     if (!isSafeToOpenFile(image)) {
  6         throw new IllegalArgumentException("Cannot open the image file.");
  7     }
  9     File f = new File(image);
 11     if (!f.exists()) {
 12         throw new WebApplicationException(404);
 13     }
 15     String mt = new MimetypesFileTypeMap().getContentType(f);
 16     return Response.ok(f, mt).build();
 17 }

File type can also be used when consuming, a temporary file will be created where the request entity is stored.

The Content-Type (if not set, see next section) can be automatically set from the MIME media types declared by @Produces if the most acceptable media type is not a wild card (one that contains a *, for example “application/” or “/*”). Given the following method:

Example 2.21. The most acceptable MIME type is used when multiple output MIME types allowed 

  1 @GET
  2 @Produces({"application/xml", "application/json"})
  3 public String doGetAsXmlOrJson() {
  4     ...
  5 }

if “application/xml” is the most acceptable then the Content-Type of the response will be set to “application/xml”.

2.5. Building Responses

Sometimes it is necessary to return additional information in response to a HTTP request. Such information may be built and returned using Response and Response.ResponseBuilder. For example, a common RESTful pattern for the creation of a new resource is to support a POST request that returns a 201 (Created) status code and a Location header whose value is the URI to the newly created resource. This may be achieved as follows:

Example 2.22. Returning 201 status code and adding Location header in response to POST request 

  1 @POST
  2 @Consumes("application/xml")
  3 public Response post(String content) {
  4     URI createdUri = ...
  5     create(content);
  6     return Response.created(createdUri).build();
  7 }

In the above no representation produced is returned, this can be achieved by building an entity as part of the response as follows:

Example 2.23. Adding an entity body to a custom response 

  1 @POST
  2 @Consumes("application/xml")
  3 public Response post(String content) {
  4     URI createdUri = ...
  5     String createdContent = create(content);
  6     return Response.created(createdUri).entity(createdContent).build();
  7 }

Response building provides other functionality such as setting the entity tag and last modified date of the representation.

2.6. Sub-resources

@Path may be used on classes and such classes are referred to as root resource classes. @Path may also be used on methods of root resource classes. This enables common functionality for a number of resources to be grouped together and potentially reused.

The first way @Path may be used is on resource methods and such methods are referred to as sub-resource methods. The following example shows the method signatures for a root resource class from the jmaki-backend sample:

Example 2.24. Sub-resource methods 

  1 @Singleton
  2 @Path("/printers")
  3 public class PrintersResource {
  5     @GET
  6     @Produces({"application/json", "application/xml"})
  7     public WebResourceList getMyResources() { ... }
  9     @GET @Path("/list")
 10     @Produces({"application/json", "application/xml"})
 11     public WebResourceList getListOfPrinters() { ... }
 13     @GET @Path("/jMakiTable")
 14     @Produces("application/json")
 15     public PrinterTableModel getTable() { ... }
 17     @GET @Path("/jMakiTree")
 18     @Produces("application/json")
 19     public TreeModel getTree() { ... }
 21     @GET @Path("/ids/{printerid}")
 22     @Produces({"application/json", "application/xml"})
 23     public Printer getPrinter(@PathParam("printerid") String printerId) { ... }
 25     @PUT @Path("/ids/{printerid}")
 26     @Consumes({"application/json", "application/xml"})
 27     public void putPrinter(@PathParam("printerid") String printerId,  Printer printer) { ... }
 29     @DELETE @Path("/ids/{printerid}")
 30     public void deletePrinter(@PathParam("printerid") String printerId) { ... }
 31 }

If the path of the request URL is “printers” then the resource methods not annotated with @Path will be selected. If the request path of the request URL is “printers/list” then first the root resource class will be matched and then the sub-resource methods that match “list” will be selected, which in this case is the sub-resource method getListOfPrinters. So in this example hierarchical matching on the path of the request URL is performed.

The second way @Path may be used is on methods not annotated with resource method designators such as @GET or @POST. Such methods are referred to as sub-resource locators. The following example shows the method signatures for a root resource class and a resource class from the optimistic-concurrency sample:

Example 2.25. Sub-resource locators 

  1 @Path("/item")
  2 public class ItemResource {
  3     @Context UriInfo uriInfo;
  5     @Path("content")
  6     public ItemContentResource getItemContentResource() {
  7         return new ItemContentResource();
  8     }
 10     @GET
 11     @Produces("application/xml")
 12     public Item get() { ... }
 13 }
 15 public class ItemContentResource {
 17     @GET
 18     public Response get() { ... }
 20     @PUT
 21     @Path("{version}")
 22     public void put(
 23             @PathParam("version") int version,
 24             @Context HttpHeaders headers,
 25             byte[] in) { ... }
 26 }

The root resource class ItemResource contains the sub-resource locator method getItemContentResource that returns a new resource class. If the path of the request URL is “item/content” then first of all the root resource will be matched, then the sub-resource locator will be matched and invoked, which returns an instance of the ItemContentResource resource class. Sub-resource locators enable reuse of resource classes.

In addition the processing of resource classes returned by sub-resource locators is performed at runtime thus it is possible to support polymorphism. A sub-resource locator may return different sub-types depending on the request (for example a sub-resource locator could return different sub-types dependent on the role of the principle that is authenticated).

Note that the runtime will not manage the life-cycle or perform any field injection onto instances returned from sub-resource locator methods. This is because the runtime does not know what the life-cycle of the instance is.

2.7. Building URIs

A very important aspects of REST is hyperlinks, URIs, in representations that clients can use to transition the Web service to new application states (this is otherwise known as “hypermedia as the engine of application state”). HTML forms present a good example of this in practice.

Building URIs and building them safely is not easy with, which is why JAX-RS has the UriBuilder class that makes it simple and easy to build URIs safely.

UriBuilder can be used to build new URIs or build from existing URIs. For resource classes it is more than likely that URIs will be built from the base URI the web service is deployed at or from the request URI. The class UriInfo provides such information (in addition to further information, see next section).

The following example shows URI building with UriInfo and UriBuilder from the bookmark sample:

Example 2.26. URI building 

  1 @Path("/users/")
  2 public class UsersResource {
  4     @Context UriInfo uriInfo;
  6     ...
  8     @GET
  9     @Produces("application/json")
 10     public JSONArray getUsersAsJsonArray() {
 11         JSONArray uriArray = new JSONArray();
 12         for (UserEntity userEntity : getUsers()) {
 13             UriBuilder ub = uriInfo.getAbsolutePathBuilder();
 14             URI userUri = ub.
 15                     path(userEntity.getUserid()).
 16                     build();
 17             uriArray.put(userUri.toASCIIString());
 18         }
 19         return uriArray;
 20     }
 21 }

UriInfo is obtained using the @Context annotation, and in this particular example injection onto the field of the root resource class is performed, previous examples showed the use of @Context on resource method parameters.

UriInfo can be used to obtain URIs and associated UriBuilder instances for the following URIs:

  • the base URI the application is deployed at
  • the request URI
  • and the absolute path URI, which is the request URI minus any query components.

The getUsersAsJsonArray method constructs a JSONArrray where each element is a URI identifying a specific user resource. The URI is built from the absolute path of the request URI by calling UriInfo.getAbsolutePathBuilder(). A new path segment is added, which is the user ID, and then the URI is built. Notice that it is not necessary to worry about the inclusion of ‘/’ characters or that the user ID may contain characters that need to be percent encoded. UriBuilder takes care of such details.

UriBuilder can be used to build/replace query or matrix parameters. URI templates can also be declared, for example the following will build the URI “http://localhost/segment?name=value”:

Example 2.27. Building URIs using query parameters 

  1 UriBuilder.fromUri("http://localhost/").
  2     path("{a}").
  3     queryParam("name", "{value}").
  4     build("segment", "value");

2.8. WebApplicationException and Mapping Exceptions to Responses

Previous sections have shown how to return HTTP responses and it is possible to return HTTP errors using the same mechanism. However, sometimes when programming in Java it is more natural to use exceptions for HTTP errors.

The following example shows the throwing of a NotFoundException from the bookmark sample:

Example 2.28. Throwing Jersey specific exceptions to control response 

  1 @Path("items/{itemid}/")
  2 public Item getItem(@PathParam("itemid") String itemid) {
  3     Item i = getItems().get(itemid);
  4     if (i == null)
  5         throw new NotFoundException("Item, " + itemid + ", is not found");
  7     return i;
  8 }

This exception is a Jersey specific exception that extends WebApplicationException and builds a HTTP response with the 404 status code and an optional message as the body of the response:

Example 2.29. Jersey specific exception implementation 

  1 public class NotFoundException extends WebApplicationException {
  3     /**
  4      * Create a HTTP 404 (Not Found) exception.
  5      */
  6     public NotFoundException() {
  7         super(Responses.notFound().build());
  8     }
 10     /**
 11      * Create a HTTP 404 (Not Found) exception.
 12      * @param message the String that is the entity of the 404 response.
 13      */
 14     public NotFoundException(String message) {
 15         super(Response.status(Responses.NOT_FOUND).
 16                 entity(message).type("text/plain").build());
 17     }
 19 }

In other cases it may not be appropriate to throw instances of WebApplicationException, or classes that extend WebApplicationException, and instead it may be preferable to map an existing exception to a response. For such cases it is possible to use the ExceptionMapper<E extends Throwable> interface. For example, the following maps the EntityNotFoundException to a HTTP 404 (Not Found) response:

Example 2.30. Mapping generic exceptions to responses 

  1 @Provider
  2 public class EntityNotFoundMapper implements
  3         ExceptionMapper<javax.persistence.EntityNotFoundException> {
  4     public Response toResponse(javax.persistence.EntityNotFoundException ex) {
  5         return Response.status(404).
  6             entity(ex.getMessage()).
  7             type("text/plain").
  8             build();
  9     }
 10 }

The above class is annotated with @Provider, this declares that the class is of interest to the JAX-RS runtime. Such a class may be added to the set of classes of the Application instance that is configured. When an application throws an EntityNotFoundException the toResponse method of the EntityNotFoundMapper instance will be invoked.

2.9. Conditional GETs and Returning 304 (Not Modified) Responses

Conditional GETs are a great way to reduce bandwidth, and potentially server-side performance, depending on how the information used to determine conditions is calculated. A well-designed web site may return 304 (Not Modified) responses for the many of the static images it serves.

JAX-RS provides support for conditional GETs using the contextual interface Request.

The following example shows conditional GET support from the sparklines sample:

Example 2.31. Conditional GET support 

  1 public SparklinesResource(
  2         @QueryParam("d") IntegerList data,
  3         @DefaultValue("0,100") @QueryParam("limits") Interval limits,
  4         @Context Request request,
  5         @Context UriInfo ui) {
  6     if (data == null)
  7         throw new WebApplicationException(400);
  9 = data;
 11     this.limits = limits;
 13     if (!limits.contains(data))
 14         throw new WebApplicationException(400);
 16     this.tag = computeEntityTag(ui.getRequestUri());
 17     if (request.getMethod().equals("GET")) {
 18         Response.ResponseBuilder rb = request.evaluatePreconditions(tag);
 19         if (rb != null)
 20             throw new WebApplicationException(;
 21     }
 22 }

The constructor of the SparklinesResouce root resource class computes an entity tag from the request URI and then calls the request.evaluatePreconditions with that entity tag. If a client request contains an If-None-Match header with a value that contains the same entity tag that was calculated then the evaluatePreconditions returns a pre-filled out response, with the 304 status code and entity tag set, that may be built and returned. Otherwise, evaluatePreconditions returns null and the normal response can be returned.

Notice that in this example the constructor of a resource class can be used perform actions that may otherwise have to be duplicated to invoked for each resource method.

2.10. Life-cycle of Root Resource Classes

By default the life-cycle of root resource classes is per-request, namely that a new instance of a root resource class is created every time the request URI path matches the root resource. This makes for a very natural programming model where constructors and fields can be utilized (as in the previous section showing the constructor of the SparklinesResource class) without concern for multiple concurrent requests to the same resource.

In general this is unlikely to be a cause of performance issues. Class construction and garbage collection of JVMs has vastly improved over the years and many objects will be created and discarded to serve and process the HTTP request and return the HTTP response.

Instances of singleton root resource classes can be declared by an instance of Application.

Jersey supports two further life-cycles using Jersey specific annotations. If a root resource class is annotated with @Singleton then only one instance is created per-web application. If a root resource class is annotated with @PerSession then one instance is created per web session and stored as a session attribute.

2.11. Security

Security information is available by obtaining the SecurityContext using @Context, which is essentially the equivalent functionality available on the HttpServletRequest.

SecurityContext can be used in conjunction with sub-resource locators to return different resources if the user principle is included in a certain role. For example, a sub-resource locator could return a different resource if a user is a preferred customer:

Example 2.32. Accessing SecurityContext 

  1 @Path("basket")
  2 public ShoppingBasketResource get(@Context SecurityContext sc) {
  3     if (sc.isUserInRole("PreferredCustomer") {
  4        return new PreferredCustomerShoppingBaskestResource();
  5     } else {
  6        return new ShoppingBasketResource();
  7     }
  8 }

2.12. Rules of Injection

Previous sections have presented examples of annotated types, mostly annotated method parameters but also annotated fields of a class, for the injection of values onto those types.

This section presents the rules of injection of values on annotated types. Injection can be performed on fields, constructor parameters, resource/sub-resource/sub-resource locator method parameters and bean setter methods. The following presents an example of all such injection cases:

Example 2.33. Injection 

  1 @Path("id: d+")
  2 public class InjectedResource {
  3     // Injection onto field
  4     @DefaultValue("q") @QueryParam("p")
  5     private String p;
  7     // Injection onto constructor parameter
  8     public InjectedResource(@PathParam("id") int id) { ... }
 10     // Injection onto resource method parameter
 11     @GET
 12     public String get(@Context UriInfo ui) { ... }
 14     // Injection onto sub-resource resource method parameter
 15     @Path("sub-id")
 16     @GET
 17     public String get(@PathParam("sub-id") String id) { ... }
 19     // Injection onto sub-resource locator method parameter
 20     @Path("sub-id")
 21     public SubResource getSubResource(@PathParam("sub-id") String id) { ... }
 23     // Injection using bean setter method
 24     @HeaderParam("X-header")
 25     public void setHeader(String header) { ... }
 26 }

There are some restrictions when injecting on to resource classes with a life-cycle other than per-request. In such cases it is not possible to injected onto fields for the annotations associated with extraction of request parameters. However, it is possible to use the @Context annotation on fields, in such cases a thread local proxy will be injected.

The @FormParam annotation is special and may only be utilized on resource and sub-resource methods. This is because it extracts information from a request entity.

2.13. Use of @Context

Previous sections have introduced the use of @ContextChapter 5 of the JAX-RS specification presents all the standard JAX-RS Java types that may be used with @Context.

When deploying a JAX-RS application using servlet then ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse are available using @Context.

2.14. Annotations Defined By JAX-RS

For a list of the annotations specified by JAX-RS see Appendix A of the specification.