Query param List of values java

RESTful Web Services Developer's Guide

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:

  • All primitive types except char

  • All wrapper classes of primitive types except Character

  • Have a constructor that accepts a single String argument

  • Any class with the static method named valueOf[String] that accepts a single String argument

  • Any class with a constructor that takes a single String as a parameter

  • List, Set, or SortedSet, 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 @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 queryParams = ui.getQueryParameters[]; MultivaluedMap pathParams = ui.getPathParameters[]; }

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

@GET public String get[@Context HttpHeaders hh] { MultivaluedMap headerParams = hh.getRequestHeaders[]; Map pathParams = hh.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 formParams] { // Store the message }

  • © 2010, Oracle Corporation and/or its affiliates

Home » Java » JAX-RS [REST] » Jersey » JAX-RS @QueryParam Example

by MemoryNotFound · Published March 16, 2016 · Updated February 12, 2018

Parameters and properties annotated with @CookieParam, @HeaderParam, @MatrixParam, @PathParam, or @QueryParam are represented as strings in a raw HTTP request. The specification says that any of these injected parameters can be converted to an object if the object's class has a valueOf[String] static method or a constructor that takes one Stringparameter. In the following, for example,

public static class Customer { private String name; public Customer[String name] { this.name = name; } public String getName[] { return name; } } @Path["test"] public static class TestResource { @GET @Path[""] public Response test[@QueryParam["cust"] Customer cust] { return Response.ok[cust.getName[]].build[]; } } @Test public void testQuery[] throws Exception { Invocation.Builder request = ClientBuilder.newClient[].target["//localhost:8081/test?cust=Bill"].request[]; Response response = request.get[]; ... }

the query "?cust=Bill" will be transformed automatically to an instance of Customer with name == "Bill".

What if you have a class where valueOf[]or this string constructor don't exist or are inappropriate for an HTTP request? JAX-RS 2.0 has the javax.ws.rs.ext.ParamConverterProvider to help in this situation.

A ParamConverterProvider is a provider defined as follows:

public interface ParamConverterProvider { public ParamConverter getConverter[Class rawType, Type genericType, Annotation annotations[]]; }

where a ParamConverter is defined:

public interface ParamConverter { ... public T fromString[String value]; public String toString[T value]; }

For example, consider DateParamConverterProvider and DateParamConverter:

@Provider public class DateParamConverterProvider implements ParamConverterProvider { @SuppressWarnings["unchecked"] @Override public ParamConverter getConverter[Class rawType, Type genericType, Annotation[] annotations] { if [rawType.isAssignableFrom[Date.class]] { return [ParamConverter] new DateParamConverter[]; } return null; } } public class DateParamConverter implements ParamConverter { public static final String DATE_PATTERN = "yyyyMMdd"; @Override public Date fromString[String param] { try { return new SimpleDateFormat[DATE_PATTERN].parse[param.trim[]]; } catch [ParseException e] { throw new BadRequestException[e]; } } @Override public String toString[Date date] { return new SimpleDateFormat[DATE_PATTERN].format[date]; } }

Sending a Date in the form of a query, e.g., "?date=20161217" will cause the string "20161217" to be converted to a Date on the server.

In addition to the JAX-RS javax.ws.rs.ext.ParamConverterProvider, RESTEasy also has its own org.jboss.resteasy.StringParameterUnmarshaller, defined

public interface StringParameterUnmarshaller { void setAnnotations[Annotation[] annotations]; T fromString[String str]; }

It is similar to javax.ws.rs.ext.ParamConverter except that

  • it converts only from Strings;
  • it is configured with the annotations on the injected parameter, which allows for fine-grained control over the injection; and
  • it is bound to a given parameter by an annotation that is annotated with the meta-annotation org.jboss.resteasy.annotations.StringParameterUnmarshallerBinder:

@Target[{ElementType.ANNOTATION_TYPE}] @Retention[RetentionPolicy.RUNTIME] public @interface StringParameterUnmarshallerBinder { Class

Chủ Đề