The Java EE 6 Tutorial, Volume I

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 of the @PathParam parameter to extract a path parameter from the path component of the request URL that matched the path declared in @Path. 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.ws.rs.QueryParam annotation in the method parameter arguments. The following example (from the sparklines sample application) demonstrates using @QueryParam to extract query parameters from the Query component of the request URL.

@Path("smooth")
@GET
public Response smooth(
        @DefaultValue("2") @QueryParam("step") int step,
        @DefaultValue("true") @QueryParam("min-m") boolean hasMin,
        @DefaultValue("true") @QueryParam("max-m") boolean hasMax,
        @DefaultValue("true") @QueryParam("last-m") boolean hasLast,           
        @DefaultValue("blue") @QueryParam("min-color") ColorParam minColor,
        @DefaultValue("green") @QueryParam("max-color") ColorParam maxColor,
        @DefaultValue("red") @QueryParam("last-color") ColorParam lastColor
        ) { ... }

If a query parameter "step" exists in the query component of the request URI, then the "step" value will be 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 an HTTP 400 (Client Error) response is returned.

User-defined Java types such as ColorParam may be used. The following code example shows how to implement this.

public class ColorParam extends Color {
    public ColorParam(String s) {
        super(getRGB(s));
    }

    private static int getRGB(String s) {
        if (s.charAt(0) == '#') {
            try {
                Color c = Color.decode("0x" + s.substring(1));
                return c.getRGB();
            } catch (NumberFormatException e) {
                throw new WebApplicationException(400);
            }
        } else {
            try {
                Field f = Color.class.getField(s);
                return ((Color)f.get(null)).getRGB();
            } catch (Exception e) {
                throw new WebApplicationException(400);
            }
        }
    }
}

@QueryParam and @PathParam can only be used on the following Java types:

If @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 List, Set, or SortedSet; null for other object types; and the Java-defined default for primitive types.

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. URI parameters are specified using the javax.ws.rs.PathParam annotation in the method parameter arguments. The following example shows how to use @Path variables and the @PathParam annotation in a method:

@Path("/{userName}")
public class MyResourceBean {
	...
	@GET
	public String printUserName(@PathParam("userName") String userId) {
		...
	}
}

In the above snippet, the URI path template variable name userName is specified as a parameter to the printUserName method. The @PathParam annotation is set to the variable name userName. At runtime, before printUserName is called, the value of userName is extracted from the URI and cast to a String. The resulting String is then available to the method as the userId variable.

If the URI path template variable cannot be cast to the specified type, the Jersey runtime returns an HTTP 400 Bad Request error to the client. If the @PathParam annotation cannot be cast to the specified type, the Jersey runtime returns an HTTP 404 Not Found error to the client.

The @PathParam parameter and the other parameter-based annotations, @MatrixParam, @HeaderParam, @CookieParam, and @FormParam obey the same rules as @QueryParam.

Cookie parameters (indicated by decorating the parameter with javax.ws.rs.CookieParam) extract information from the cookies declared in cookie-related HTTP headers. Header parameters (indicated by decorating the parameter with javax.ws.rs.HeaderParam) extracts information from the HTTP headers. Matrix parameters (indicated by decorating the parameter with javax.ws.rs.MatrixParam) extracts information from URL path segments. These parameters are beyond the scope of this tutorial.

Form parameters (indicated by decorating the parameter with javax.ws.rs.FormParam) 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, as described here. This parameter is very useful for extracting information that is POSTed by HTML forms. The following example extracts the form parameter named "name" from the POSTed form data.

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

If it is necessary to obtain a general map of parameter names to values, use code such as that shown in the following example , for query and path parameters.

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

Or code such as the following for header and cookie parameters:

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

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:

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