Introducing JAX-RS API

 In this article by Jobinesh Purushothaman, author of the book, RESTful Java Web Services, Second Edition, we will see that there are many tools and frameworks available in the market today for building RESTful web services. There are some recent developments with respect to the standardization of various framework APIs by providing unified interfaces for a variety of implementations. Let's take a quick look at this effort.

(For more resources related to this topic, see here.)

As you may know, Java EE is the industry standard for developing portable, robust, scalable, and secure server-side Java applications. The Java EE 6 release took the first step towards standardizing RESTful web service APIs by introducing a Java API for RESTful web services (JAX-RS). JAX-RS is an integral part of the Java EE platform, which ensures portability of your REST API code across all Java EE-compliant application servers. The first release of JAX-RS was based on JSR 311. The latest version is JAX-RS 2 (based on JSR 339), which was released as part of the Java EE 7 platform. There are multiple JAX-RS implementations available today by various vendors. Some of the popular JAX-RS implementations are as follows:

  • Jersey RESTful web service framework: This framework is an open source framework for developing RESTful web services in Java. It serves as a JAX-RS reference implementation. You can learn more about this project at https://jersey.java.net.
  • Apache CXF: This framework is an open source web services framework. CXF supports both JAX-WS and JAX-RS web services. To learn more about CXF, refer to http://cxf.apache.org.
  • RESTEasy: This framework is an open source project from JBoss, which provides various modules to help you build a RESTful web service. To learn more about RESTEasy, refer to http://resteasy.jboss.org.
  • Restlet: This framework is a lightweight, open source RESTful web service framework. It has good support for building both scalable RESTful web service APIs and lightweight REST clients, which suits mobile platforms well. You can learn more about Restlet at http://restlet.com.

Remember that you are not locked down to any specific vendor here, the RESTful web service APIs that you build using JAX-RS will run on any JAX-RS implementation as long as you do not use any vendor-specific APIs in the code.

JAX-RS annotations                                     

The main goal of the JAX-RS specification is to make the RESTful web service development easier than it has been in the past. As JAX-RS is a part of the Java EE platform, your code becomes portable across all Java EE-compliant servers.

Specifying the dependency of the JAX-RS API

To use JAX-RS APIs in your project, you need to add the javax.ws.rs-api JAR file to the class path. If the consuming project uses Maven for building the source, the dependency entry for the javax.ws.rs-api JAR file in the Project Object Model (POM) file may look like the following:

<dependency>
   <groupId>javax.ws.rs</groupId>
   <artifactId>javax.ws.rs-api</artifactId>
   <version>2.0.1</version><!-- set the tight version -->
   <scope>provided</scope><!-- compile time dependency -->
</dependency>

Using JAX-RS annotations to build RESTful web services

Java annotations provide the metadata for your Java class, which can be used during compilation, during deployment, or at runtime in order to perform designated tasks. The use of annotations allows us to create RESTful web services as easily as we develop a POJO class. Here, we leave the interception of the HTTP requests and representation negotiations to the framework and concentrate on the business rules necessary to solve the problem at hand.

If you are not familiar with Java annotations, go through the tutorial available at http://docs.oracle.com/javase/tutorial/java/annotations/.

Annotations for defining a RESTful resource

REST resources are the fundamental elements of any RESTful web service. A REST resource can be defined as an object that is of a specific type with the associated data and is optionally associated to other resources. It also exposes a set of standard operations corresponding to the HTTP method types such as the HEAD, GET, POST, PUT, and DELETE methods.

@Path

The @javax.ws.rs.Path annotation indicates the URI path to which a resource class or a class method will respond. The value that you specify for the @Path annotation is relative to the URI of the server where the REST resource is hosted. This annotation can be applied at both the class and the method levels.

A @Path annotation value is not required to have leading or trailing slashes (/), as you may see in some examples. The JAX-RS runtime will parse the URI path templates in the same way even if they have leading or trailing slashes.

Specifying the @Path annotation on a resource class

The following code snippet illustrates how you can make a POJO class respond to a URI path template containing the /departments path fragment:

import javax.ws.rs.Path;

@Path("departments")
public class DepartmentService {
//Rest of the code goes here
}

The /department path fragment that you see in this example is relative to the base path in the URI. The base path typically takes the following URI pattern: http://host:port/<context-root>/<application-path>.

Specifying the @Path annotation on a resource class method

The following code snippet shows how you can specify @Path on a method in a REST resource class. Note that for an annotated method, the base URI is the effective URI of the containing class. For instance, you will use the URI of the following form to invoke the getTotalDepartments() method defined in the DepartmentService class: /departments/count, where departments is the @Path annotation set on the class.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("departments")
public class DepartmentService {
   @GET
   @Path("count")
   @Produces("text/plain")
   public Integer getTotalDepartments() {
       return findTotalRecordCount();
   }
//Rest of the code goes here
}
Specifying variables in the URI path template

It is very common that a client wants to retrieve data for a specific object by passing the desired parameter to the server. JAX-RS allows you to do this via the URI path variables as discussed here.

The URI path template allows you to define variables that appear as placeholders in the URI. These variables would be replaced at runtime with the values set by the client.

The following example illustrates the use of the path variable to request for a specific department resource. The URI path template looks like /departments/{id}. At runtime, the client can pass an appropriate value for the id parameter to get the desired resource from the server. For instance, the URI path of the /departments/10 format returns the IT department details to the caller.

The following code snippet illustrates how you can pass the department ID as a path variable for deleting a specific department record. The path URI looks like /departments/10.

import javax.ws.rs.Path;
import javax.ws.rs.DELETE;

@Path("departments")
public class DepartmentService {

@DELETE
@Path("{id}")
public void removeDepartment(@PathParam("id")
short id) {
   removeDepartmentEntity(id);
}
//Other methods removed for brevity
}

In the preceding code snippet, the @PathParam annotation is used for copying the value of the path variable to the method parameter.

Restricting values for path variables with regular expressions

JAX-RS lets you use regular expressions in the URI path template for restricting the values set for the path variables at runtime by the client. By default, the JAX-RS runtime ensures that all the URI variables match the following regular expression: [^/]+?. The default regular expression allows the path variable to take any character except the forward slash (/). What if you want to override this default regular expression imposed on the path variable values? Good news is that JAX-RS lets you specify your own regular expression for the path variables. For example, you can set the regular expression as given in the following code snippet in order to ensure that the department name variable present in the URI path consists only of lowercase and uppercase alphanumeric characters:

@DELETE
@Path("{name: [a-zA-Z][a-zA-Z_0-9]}")
public void removeDepartmentByName(@PathParam("name")
String deptName) {
   //Method implementation goes here
}

If the path variable does not match the regular expression set of the resource class or method, the system reports the status back to the caller with an appropriate HTTP status code, such as 404 Not Found, which tells the caller that the requested resource could not be found at this moment.

Annotations for specifying request-response media types

The Content-Type header field in HTTP describes the body's content type present in the request and response messages. The content types are represented using the standard Internet media types. A RESTful web service makes use of this header field to indicate the type of content in the request or response message body.

JAX-RS allows you to specify which Internet media types of representations a resource can produce or consume by using the @javax.ws.rs.Produces and @javax.ws.rs.Consumes annotations, respectively.

@Produces

The @javax.ws.rs.Produces annotation is used for defining the Internet media type(s) that a REST resource class method can return to the client. You can define this either at the class level (which will get defaulted for all methods) or the method level. The method-level annotations override the class-level annotations. The possible Internet media types that a REST API can produce are as follows:

  • application/atom+xml
  • application/json
  • application/octet-stream
  • application/svg+xml
  • application/xhtml+xml
  • application/xml
  • text/html
  • text/plain
  • text/xml

The following example uses the @Produces annotation at the class level in order to set the default response media type as JSON for all resource methods in this class. At runtime, the binding provider will convert the Java representation of the return value to the JSON format.

import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("departments")
@Produces(MediaType.APPLICATION_JSON)
public class DepartmentService{
//Class implementation goes here...  
}

@Consumes

The @javax.ws.rs.Consumes annotation defines the Internet media type(s) that the resource class methods can accept. You can define the @Consumes annotation either at the class level (which will get defaulted for all methods) or the method level. The method-level annotations override the class-level annotations. The possible Internet media types that a REST API can consume are as follows:

  • application/atom+xml
  • application/json
  • application/octet-stream
  • application/svg+xml
  • application/xhtml+xml
  • application/xml
  • text/html
  • text/plain
  • text/xml
  • multipart/form-data
  • application/x-www-form-urlencoded

The following example illustrates how you can use the @Consumes attribute to designate a method in a class to consume a payload presented in the JSON media type. The binding provider will copy the JSON representation of an input message to the Department parameter of the createDepartment() method.

import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.POST;

@POST
@Consumes(MediaType.APPLICATION_JSON)
public void createDepartment(Department entity) {
//Method implementation goes here…
}

The javax.ws.rs.core.MediaType class defines constants for all media types supported in JAX-RS. To learn more about the MediaType class, visit the API documentation available at http://docs.oracle.com/javaee/7/api/javax/ws/rs/core/MediaType.html.

Annotations for processing HTTP request methods

In general, RESTful web services communicate over HTTP with the standard HTTP verbs (also known as method types) such as GET, PUT, POST, DELETE, HEAD, and OPTIONS.

@GET

A RESTful system uses the HTTP GET method type for retrieving the resources referenced in the URI path. The @javax.ws.rs.GET annotation designates a method of a resource class to respond to the HTTP GET requests.

The following code snippet illustrates the use of the @GET annotation to make a method respond to the HTTP GET request type. In this example, the REST URI for accessing the findAllDepartments() method may look like /departments. The complete URI path may take the following URI pattern: http://host:port/<context-root>/<application-path>/departments.

//imports removed for brevity
@Path("departments")
public class DepartmentService {
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Department> findAllDepartments() {
   //Find all departments from the data store
   List<Department> departments = findAllDepartmentsFromDB();
   return departments;
}
//Other methods removed for brevity
}

@PUT

The HTTP PUT method is used for updating or creating the resource pointed by the URI. The @javax.ws.rs.PUT annotation designates a method of a resource class to respond to the HTTP PUT requests. The PUT request generally has a message body carrying the payload. The value of the payload could be any valid Internet media type such as the JSON object, XML structure, plain text, HTML content, or binary stream. When a request reaches a server, the framework intercepts the request and directs it to the appropriate method that matches the URI path and the HTTP method type. The request payload will be mapped to the method parameter as appropriate by the framework.

The following code snippet shows how you can use the @PUT annotation to designate the editDepartment() method to respond to the HTTP PUT request. The payload present in the message body will be converted and copied to the department parameter by the framework:

@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
public void editDepartment(@PathParam("id") Short id,
Department department) {
//Updates department entity to data store
updateDepartmentEntity(id, department);
}

@POST

The HTTP POST method posts data to the server. Typically, this method type is used for creating a resource. The @javax.ws.rs.POST annotation designates a method of a resource class to respond to the HTTP POST requests.

The following code snippet shows how you can use the @POST annotation to designate the createDepartment() method to respond to the HTTP POST request. The payload present in the message body will be converted and copied to the department parameter by the framework:

@POST
public void createDepartment(Department department) {
//Create department entity in data store
createDepartmentEntity(department);

}

@DELETE

The HTTP DELETE method deletes the resource pointed by the URI. The @javax.ws.rs.DELETE annotation designates a method of a resource class to respond to the HTTP DELETE requests.

The following code snippet shows how you can use the @DELETE annotation to designate the removeDepartment() method to respond to the HTTP DELETE request. The department ID is passed as the path variable in this example.

@DELETE
@Path("{id}")
public void removeDepartment(@PathParam("id") Short id) {
//remove department entity from data store
removeDepartmentEntity(id);
}

@HEAD

The @javax.ws.rs.HEAD annotation designates a method to respond to the HTTP HEAD requests. This method is useful for retrieving the metadata present in the response headers, without having to retrieve the message body from the server. You can use this method to check whether a URI pointing to a resource is active or to check the content size by using the Content-Length response header field, and so on.

The JAX-RS runtime will offer the default implementations for the HEAD method type if the REST resource is missing explicit implementation. The default implementation provided by runtime for the HEAD method will call the method designated for the GET request type, ignoring the response entity retuned by the method.

@OPTIONS

The @javax.ws.rs.OPTIONS annotation designates a method to respond to the HTTP OPTIONS requests. This method is useful for obtaining a list of HTTP methods allowed on a resource.

The JAX-RS runtime will offer a default implementation for the OPTIONS method type, if the REST resource is missing an explicit implementation. The default implementation offered by the runtime sets the Allow response header to all the HTTP method types supported by the resource.

Annotations for accessing request parameters

You can use this offering to extract the following parameters from a request: a query, URI path, form, cookie, header, and matrix. Mostly, these parameters are used in conjunction with the GET, POST, PUT, and DELETE methods.

@PathParam

A URI path template, in general, has a URI part pointing to the resource. It can also take the path variables embedded in the syntax; this facility is used by clients to pass parameters to the REST APIs as appropriate. The @javax.ws.rs.PathParam annotation injects (or binds) the value of the matching path parameter present in the URI path template into a class field, a resource class bean property (the getter method for accessing the attribute), or a method parameter. Typically, this annotation is used in conjunction with the HTTP method type annotations such as @GET, @POST, @PUT, and @DELETE.

The following example illustrates the use of the @PathParam annotation to read the value of the path parameter, id, into the deptId method parameter. The URI path template for this example looks like /departments/{id}:

//Other imports removed for brevity
javax.ws.rs.PathParam

@Path("departments")
public class DepartmentService {
   @DELETE
   @Path("{id}")
   public void removeDepartment(@PathParam("id") Short deptId) {
     removeDepartmentEntity(deptId);
   }
   //Other methods removed for brevity
}

The REST API call to remove the department resource identified by id=10 looks like DELETE /departments/10 HTTP/1.1.

We can also use multiple variables in a URI path template. For example, we can have the URI path template embedding the path variables to query a list of departments from a specific city and country, which may look like /departments/{country}/{city}. The following code snippet illustrates the use of @PathParam to extract variable values from the preceding URI path template:

@Produces(MediaType.APPLICATION_JSON)
@Path("{country}/{city} ")
public List<Department> findAllDepartments(
@PathParam("country")
String countyCode,   @PathParam("city") String cityCode) {
//Find all departments from the data store for a country
//and city
List<Department> departments =
   findAllMatchingDepartmentEntities(countyCode,
     cityCode );
   return departments;
}

@QueryParam

The @javax.ws.rs.QueryParam annotation injects the value(s) of a HTTP query parameter into a class field, a resource class bean property (the getter method for accessing the attribute), or a method parameter.

The following example illustrates the use of @QueryParam to extract the value of the desired query parameter present in the URI. This example extracts the value of the query parameter, name, from the request URI and copies the value into the deptName method parameter. The URI that accesses the IT department resource looks like /departments?name=IT:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Department>
findAllDepartmentsByName(@QueryParam("name") String deptName) {
   List<Department> depts= findAllMatchingDepartmentEntities
     (deptName);
return depts;      
}

@MatrixParam

Matrix parameters are another way of defining parameters in the URI path template. The matrix parameters take the form of name-value pairs in the URI path, where each pair is preceded by semicolon (;). For instance, the URI path that uses a matrix parameter to list all departments in Bangalore city looks like /departments;city=Bangalore.

The @javax.ws.rs.MatrixParam annotation injects the matrix parameter value into a class field, a resource class bean property (the getter method for accessing the attribute), or a method parameter.

The following code snippet demonstrates the use of the @MatrixParam annotation to extract the matrix parameters present in the request. The URI path used in this example looks like /departments;name=IT;city=Bangalore.

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("matrix")
public List<Department>
findAllDepartmentsByNameWithMatrix(@MatrixParam("name") String
   deptName, @MatrixParam("city") String locationCode) {
List<Department> depts=findAllDepartmentsFromDB(deptName,
   city);
return depts;
}

You can use PathParam, QueryParam, and MatrixParam to pass the desired search parameters to the REST APIs. Now, you may ask when to use what?

Although there are no strict rules here, a very common practice followed by many is to use PathParam to drill down to the entity class hierarchy. For example, you may use the URI of the following form to identify an employee working in a specific department: /departments/{dept}/employees/{id}.

QueryParam can be used for specifying attributes to locate the instance of a class. For example, you may use URI with QueryParam to identify employees who have joined on January 1, 2015, which may look like /employees?doj=2015-01-01.

The MatrixParam annotation is not used frequently. This is useful when you need to make a complex REST style query to multiple levels of resources and subresources. MatrixParam is applicable to a particular path element, while the query parameter is applicable to the entire request.

@HeaderParam

The HTTP header fields provide necessary information about the request and response contents in HTTP. For example, the header field, Content-Length: 348, for an HTTP request says that the size of the request body content is 348 octets (8-bit bytes). The @javax.ws.rs.HeaderParam annotation injects the header values present in the request into a class field, a resource class bean property (the getter method for accessing the attribute), or a method parameter.

The following example extracts the referrer header parameter and logs it for audit purposes. The referrer header field in HTTP contains the address of the previous web page from which a request to the currently processed page originated:

@POST
public void createDepartment(@HeaderParam("Referer")
String referer, Department entity) {
logSource(referer);
createDepartmentInDB(department);
}

Remember that HTTP provides a very wide selection of headers that cover most of the header parameters that you are looking for. Although you can use custom HTTP headers to pass some application-specific data to the server, try using standard headers whenever possible. Further, avoid using a custom header for holding properties specific to a resource, or the state of the resource, or parameters directly affecting the resource.

@CookieParam

The @javax.ws.rs.CookieParam annotation injects the matching cookie parameters present in the HTTP headers into a class field, a resource class bean property (the getter method for accessing the attribute), or a method parameter.

The following code snippet uses the Default-Dept cookie parameter present in the request to return the default department details:

@GET
@Path("cook")
@Produces(MediaType.APPLICATION_JSON)
public Department getDefaultDepartment(@CookieParam("Default-Dept")
short departmentId) {
Department dept=findDepartmentById(departmentId);
return dept;
}
@FormParam

The @javax.ws.rs.FormParam annotation injects the matching HTML form parameters present in the request body into a class field, a resource class bean property (the getter method for accessing the attribute), or a method parameter. The request body carrying the form elements must have the content type specified as application/x-www-form-urlencoded.

Consider the following HTML form that contains the data capture form for a department entity. This form allows the user to enter the department entity details:

<!DOCTYPE html>
<html>
<head>
<title>Create Department</title>
</head>
<body>
   <form method="POST" action="/resources/departments">
   Department Id:
   <input type="text" name="departmentId">
   <br>
   Department Name:
     <input type="text" name="departmentName">
     <br>
     <input type="submit" value="Add Department" />
   </form>
</body>
</html>

Upon clicking on the submit button on the HTML form, the department details that you entered will be posted to the REST URI, /resources/departments. The following code snippet shows the use of the @FormParam annotation for extracting the HTML form fields and copying them to the resource class method parameter:

@Path("departments")
public class DepartmentService {

@POST
//Specifies content type as
//"application/x-www-form-urlencoded"
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void createDepartment(@FormParam("departmentId") short
   departmentId,
     @FormParam("departmentName") String departmentName) {
     createDepartmentEntity(departmentId, departmentName);
}
}

@DefaultValue

The @javax.ws.rs.DefaultValue annotation specifies a default value for the request parameters accessed using one of the following annotations: PathParam, QueryParam, MatrixParam, CookieParam, FormParam, or HeaderParam. The default value is used if no matching parameter value is found for the variables annotated using one of the preceding annotations.

The following REST resource method will make use of the default value set for the from and to method parameters if the corresponding query parameters are found missing in the URI path:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Department> findAllDepartmentsInRange
(@DefaultValue("0") @QueryParam("from") Integer from,
   @DefaultValue("100") @QueryParam("to") Integer to) {
   findAllDepartmentEntitiesInRange(from, to);
}

@Context

The JAX-RS runtime offers different context objects, which can be used for accessing information associated with the resource class, operating environment, and so on. You may find various context objects that hold information associated with the URI path, request, HTTP header, security, and so on. Some of these context objects also provide the utility methods for dealing with the request and response content. JAX-RS allows you to reference the desired context objects in the code via dependency injection. JAX-RS provides the @javax.ws.rs.Context annotation that injects the matching context object into the target field. You can specify the @Context annotation on a class field, a resource class bean property (the getter method for accessing the attribute), or a method parameter.

The following example illustrates the use of the @Context annotation to inject the javax.ws.rs.core.UriInfo context object into a method variable. The UriInfo instance provides access to the application and request URI information. This example uses UriInfo to read the query parameter present in the request URI path template, /departments/IT:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Department> findAllDepartmentsByName(
@Context UriInfo uriInfo){
String deptName =
   uriInfo.getPathParameters().getFirst("name");
List<Department> depts= findAllMatchingDepartmentEntities
   (deptName);
return depts;
}

Here is a list of the commonly used classes and interfaces, which can be injected using the @Context annotation:

  • javax.ws.rs.core.Application: This class defines the components of a JAX-RS application and supplies additional metadata
  • javax.ws.rs.core.UriInfo: This interface provides access to the application and request URI information
  • javax.ws.rs.core.Request: This interface provides a method for request processing such as reading the method type and precondition evaluation.
  • javax.ws.rs.core.HttpHeaders: This interface provides access to the HTTP header information
  • javax.ws.rs.core.SecurityContext: This interface provides access to security-related information
  • javax.ws.rs.ext.Providers: This interface offers the runtime lookup of a provider instance such as MessageBodyReader, MessageBodyWriter, ExceptionMapper, and ContextResolver
  • javax.ws.rs.ext.ContextResolver<T>: This interface supplies the requested context to the resource classes and other providers
  • javax.servlet.http.HttpServletRequest: This interface provides the client request information for a servlet
  • javax.servlet.http.HttpServletResponse: This interface is used for sending a response to a client
  • javax.servlet.ServletContext: This interface provides methods for a servlet to communicate with its servlet container
  • javax.servlet.ServletConfig: This interface carries the servlet configuration parameters

@BeanParam

The @javax.ws.rs.BeanParam annotation allows you to inject all matching request parameters into a single bean object. The @BeanParam annotation can be set on a class field, a resource class bean property (the getter method for accessing the attribute), or a method parameter. The bean class can have fields or properties annotated with one of the request parameter annotations, namely @PathParam, @QueryParam, @MatrixParam, @HeaderParam, @CookieParam, or @FormParam. Apart from the request parameter annotations, the bean can have the @Context annotation if there is a need.

Consider the example that we discussed for @FormParam. The createDepartment() method that we used in that example has two parameters annotated with @FormParam:

public void createDepartment(
@FormParam("departmentId") short departmentId,
   @FormParam("departmentName") String departmentName)

Let's see how we can use @BeanParam for the preceding method to give a more logical, meaningful signature by grouping all the related fields into an aggregator class, thereby avoiding too many parameters in the method signature.

The DepartmentBean class that we use for this example is as follows:

public class DepartmentBean {

@FormParam("departmentId")
   private short departmentId;

@FormParam("departmentName")
   private String departmentName;

//getter and setter for the above fields
//are not shown here to save space
}

The following code snippet demonstrates the use of the @BeanParam annotation to inject the DepartmentBean instance that contains all the FormParam values extracted from the request message body:

@POST
public void createDepartment(@BeanParam DepartmentBean deptBean)
{
createDepartmentEntity(deptBean.getDepartmentId(),
   deptBean.getDepartmentName());
}

@Encoded

By default, the JAX-RS runtime decodes all request parameters before injecting the extracted values into the target variables annotated with one of the following annotations: @FormParam, @PathParam, @MatrixParam, or @QueryParam. You can use @javax.ws.rs.Encoded to disable the automatic decoding of the parameter values. With the @Encoded annotation, the value of parameters will be provided in the encoded form itself. This annotation can be used on a class, method, or parameters. If you set this annotation on a method, it will disable decoding for all parameters defined for this method. You can use this annotation on a class to disable decoding for all parameters of all methods. In the following example, the value of the path parameter called name is injected into the method parameter in the URL encoded form (without decoding). The method implementation should take care of the decoding of the values in such cases:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Department>
findAllDepartmentsByName(@QueryParam("name") String deptName) {
//Method body is removed for brevity
}

URL encoding converts a string into a valid URL format, which may contain alphabetic characters, numerals, and some special characters supported in the URL string. To learn about the URL specification, visit http://www.w3.org/Addressing/URL/url-spec.html.

Summary

With the use of annotations, the JAX-RS API provides a simple development model for RESTful web service programming.

In case you are interested in knowing other Java RESTful Web Services books that Packt has in store for you, here is the link:

Resources for Article:


Further resources on this subject:


You've been reading an excerpt of:

RESTful Java Web Services - Second Edition

Explore Title