JAX-RS Parameter Annotations

1. Overview

This guide covers all the standard JAX-RS Parameter Annotations used for Rest API development.
  • @PathParam
  • @DefaultValue
  • @QueryParam
  • @FormParam
  • @MatrixParam
  • @CookieParam
  • @HeaderParam
Let's see each annotation with an example.

2. The @PathParam Annotation

@PathParam to extract a path parameter from the path component of the request URL that matched the path declared in @Path. Example:
    @Path("{userid}/")
    public String getUser(@PathParam("userid") String userid) {
       // return user object as json
    }
@Path("/users/{username}")
public class UserResource {
 
    @GET
    @Produces("text/xml")
    public String getUser(@PathParam("username") String userName) {
        ...
    }
}

3. The @QueryParam Annotation

A query parameter is a value associated with the key/value pair appended to a URL after the ?symbol. So for example, in the URL: http://localhost:8080/api/books/search?keyword=Java&limit=10 the query parameters are keyword and limit and the query values are Java and 10.
To retrieve these values use the @QueryParam annotation and pass the name of the query parameter as a value to the annotation, then annotated a method parameter in the resource method that responds to a request to the URI resource /books/search.
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("search")
public Response searchBook(@QueryParam("keyword") String keyword, @QueryParam("limit") int limit) {
    List<Book> books = bookRepository.searchBook(keyword, limit);
    return Response.ok(new GenericEntity<List<Book>>(books) {}).build();
}
In the code snippet above the value of the keyword query parameter is assigned to the method parameter keyword and the value of the limit query parameter is assigned to the limit method parameter.

4. The @FormParam Annotation

@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: Processing POSTed HTML form
@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name) {
    // Store the message
}
On other words, You may need to read parameters sent in a POST HTTP requests directly from the body, rather than serializing it to an object. This can be done by using the @FormParam annotation.
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response saveBookF(@FormParam("title") String title,
                          @FormParam("author") String author,
                          @FormParam("price") Float price) {
    return Response.ok(bookRepository.saveBook(new Book(title, author, price))).build();
}

5. The @MatrixParam Annotation

Matrix parameters are a set of query parameters separated by a semicolon rather than an ampersand. This may occur because the values were selected from a multiple select input box and being set via a GET request rather than a POST request. The URL might look something like this:
http://localhost:8080/api/books;author=atheedom;category=Java;language=english
The annotation @MatricParam is used to retrieve the parameter value from the URI and assign it to a method parameter.
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getBookBy(@MatrixParam("author") String author,
                          @MatrixParam("category") String category,
                          @MatrixParam("language") String language) {
    return Response.ok(
            new GenericEntity<List<Book>>(
                    bookRepository.getBookBy(author, category, language)) {}).build();
}

6. The @CookieParam Annotation

The @CookieParam annotation allows you to inject directly into your resource method cookies sent by the client. Imagine you have sent a cookie called cartId to the clients so that you can track the customer’s shopping cart. To pull the cookie from the HTTP request just annotate the method parameter to which you want the cookie data to be assigned.
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getCart(@CookieParam("cartId") int cartId) {
    return Response.ok().build();
}

7. The @HeaderParam Annotation

The @HeaderParam annotation is used to inject HTTP request header values into resource method parameters. You can think of it like a shortcut to using the @Context annotation to inject theHttpServletRequest or HttpHeaders instance.
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getReferrer(@HeaderParam("referer") String referrer) {
    return Response.ok(referrer).build();
}

Conclusion

This post explained the JAX-RS Parameter Annotations.
Learn more about Jersey Rest framework on Jersey Rest Developer Guide.
All the code of this post is available over on Github. This is a Maven-based project, so it should be easy to import and run as it is.

Comments