Chapter 1
Introduction to RESTful Web Services and Jersey
1. What are RESTful Web Services?
RESTful - REpresentational State Transfer is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web.
Data and functionality are considered resources, and these resources are accessed using URIs (Unifomr Resource Identifiers), typically links on the web.
The REST architectural style constrains an architecture to a client-server architecture, and is designed to use a stateless communication protocol, typically HTTP. Clients and servers exchange representations of resources using a standardized interface and protocol.
RESTful web services typically map the four main HTTP methods to the operations they perform: create, retrieve, update and delete.
GET — Get a resource; POST — Create a resource and other operations, as it has no defined semantics; PUT — Create or update a resource; DELETE — delete a resource
2. How does Jersey fit in?
Jersey is Sun’s production quality reference implementation for JSR 311: JAX-RS: The Java API for RESTful Web Services. Jersey implements support for the annotations defined in JSR-311, making it easy for developers to build RESTful web services with Java and Java JVM. Jersey also adds additional features not specified by the JSR.
Chapter 3
Creating a RESTful resource class
Root resource classes are POJOs that are either annotated with @Path or have at least one method annotated with @Path or a request method designator such as @GET, @PUT, @POST, or @DELETE.
Resource methods are methods of a resource class annotated with a request method designator.
1. Developing RESTful web services with Jersey
Developers decorate Java programming language class files with HTTP-specific annotations to define resources and the actions that can be performed on those resources. Jersey annotations are runtime annotations, therefore, runtime reflection will generate the helper classes and artifacts for the resource, and then the collection of classes and artifacts will be built into a WAR. The resources are exposed to clients by deploying the WAR to a Java EE or web server.
@Path annotation’s value is a relative URI path. 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.
@GET annotation is a request method designator, along with @POST, @PUT, @DELETE, and @HEAD, that is defined by JAX-RS, and which correspond to the similarly named HTTP methods.
@Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client.
@Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client.
2. What are some of the annotations defined by JAX-RS?
| Annotations |
Description |
| @Path |
The @Path annotation’s value is a relative URI path indicating where the Java class will be hosted, for example, /helloworld. You can also embed variables in the URIs to make a URI path template. For example, you could ask for the name of a user, and pass it to the application as a variable in the URI, like this, /helloworld/{username}. |
| @GET |
The @GET annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP GET requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. |
| @POST |
The @POST annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP POST requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. |
| @PUT |
The @PUT annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP PUT requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. |
| @DELETE |
The @DELETE annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. |
| @HEAD |
The @HEAD annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP HEAD requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. |
| @PathParam |
The @PathParam annotation is a type of parameter that you can extract for use in your resource class. URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation. |
| @QueryParam |
The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters. |
| @Consumes |
The @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client. |
| @Produces |
The @Produces annotation is used to specify the MIME media type of representations a resource can produce and send back to the client, for example, “text/plain”. |
| @Provider |
The @Provider annotation is used for anything that is of interest to the JAX-RS runtime, such as MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is used to map an HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP response entity body using MessageBodyWriter. If the application needs to supply additional metadata, such as HTTP headers or a different status code, a method can return a Response that wraps the entity, and which can be built using Response.ResponseBuilder. |
3. The @Path annotation and URI path templates.
The @Path annotation identifies the URI path template to which the resource responds, and is specified at the class level of a resource. 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.
@Path (”/users/{username}”)
if user entered user name as Galileo, the web service will respond to the following URL: http://example.com/users/Galileo
The @PathParam annotation may be used on the method parameter of a request method to obtain the value of the username variable.
public class UserResource{
@GET
@Produces(”text/xml”)
public String getUser(@PathParam(”username”) String userName){
…
}
}
By default, there is no difference between @Path value begin or not begin with a forward slash(/) and end with a forward slash(/) as well. However, Jersey has a redirection mechanism, if enabled, will perform redirection.
4. Responding to HTTP Resources
The behavior of a resource is determined by the HTTP methods (typically GET, POST, PUT, and DELETE) to which the resource is responding.
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 resources. In addition Jersey will return a WADL document describing the resource.
Method decorated with request method designators must return void, a Java programming language type, or a javax.ws.rs.core.Response object. Multiple parameters may be extracted from the URI using the PathParam or QueryParam annotations. Conversion between Java types and entity body is the responsibility of an entity provider, such as MessageBodyReader or MessageBodyWriter. Methods that need to provide additional metadata with a response should return an instance of Response. The ResponseBuilder class provides a convenient way to create a Response instance using a builder pattern. The HTTP PUT and POST methods expect an HTTP request body, so you should use a MessageBodyReader for methods that respond to PUT and POST requests.
5. Using entity providers to map HTTP response and request entity bodies.
Entity providers supply mapping services between representations and their associated Java types.
The following list contains the standard types that are supported automatically for entities. You only need to write an entity provider if you are not choosing one of the following standard types.
6. Using @Consumes and @Produces to customize requests and responses
The @Produces annotation is used to specify the MIME media types or representations a resource can produce and send back to the client. If @Produces is applied at the class level, all the methods in a resource can produce the specified MIME types by default. If it is applied at the method level, it overrides any @Produces annotations applied at the class level.
If no methods in a resource are able to produce the MIME type in a client request, the Jersey runtime sends back an HTTP “406 Not Acceptable” error.
The value of @Produces is an array of String of MIME types.
If a resource class is capable of producing more than one MIME media type, 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.
The @Consumes annotation is used to specify which MIME media types of representations a resource can accept, from the client. If @Consumes is applied at the class level, all the response methods accept the specified MIME types by default. If @Consumes is applied at the method level, it overrides any @Consumes annotations applied at the class level.
If a resource is unable to consume the MIME type of a client request, the Jersey runtime sends back an HTTP “415 Unsupported Media Type” error.
The value of @Consumes is an array of String of acceptable MIME types.
7. Extracting Request Parameters
Parameters of a resource method may be annotated with parameter-based annotations to extract information from a request. There are six types of parameters you can extract for use in your resource class: query parameters, URI path parameters, form parameters, cookie parameters, header parameters, and matrix parameters.
Query parameters are extracted from the request URI query parameters, and are specified by using the javax.rs.QueryParam annotation in the method parameter arguments.
@QueryParam and @PathParam can only be used on the following Java types: all primitive types except char, all wrapper class of primitive types except Character, have a constructor that accepts a single String argument, any class with the static method named valueOf(String) that accpets a single String argument, any class with a constructor that takes a single String as a parameter, List<T>, Set<T>, or SortedSet<T>, where T matches the already listed criteria. Sometimes parameters may contain more than one value for the same name. If this is the case, these types may be used to obtain all values.
If @DefaultValue is not used in conjunction with @QueryOaram, and the query parameter is not present in the request, then value will be an empty collection for List, Set, or SortedSet; null for other object types; and the Java-defined default for primitive types.
URI path parametes are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation. URI parameters are specified using the javax.ws.rs.PathParam annotation in the method paraeter arguments.
Form parameters extract 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.
@Context can be used to obtain contextual Java types related to the request or response.