Retrieving query parameters in JAX-RS annotated method

The post explains different ways of retrieving query parameters in JAX-RS annotated method.

Below is the complete code

1  package resource;
3  import;
4  import;
5  import;
6  import;
7  import;
8  import;
9  import;
11 @Path("webresource2")
12 public class WebResource2 {
13  @GET
14  @Path("queryParameters1")
15  public Response getQueryParameters1(@QueryParam("param1") String param1) {
16      Response response = Response.ok(param1, MediaType.TEXT_PLAIN).build();
17      return response;
18  }
20  @GET
21  @Path("queryParameters2")
22  public Response getQueryParameters2(@Context UriInfo info) {
23      String value = info.getQueryParameters().getFirst("param1");
24      Response response = Response.ok(value, MediaType.TEXT_PLAIN).build();
25      return response;
26  }
27 }

The above web resource can be accessed using the below two urls

In the first method getQueryParameters1, the variable param1 is annotated by QueryParam. This to inform to the JAX-RS runtime that the value has to be taken from the request query parameter using header name passed to the QueryParam annotation (i.e., in this param1) and inject the value to the variable param1.

In the second method getQueryParameters2, we use the Context annotation. This annotation is used to inject context information, in this case UriInfo instance. UriInfo instance provides both static and dynamic per request information, about the components of the request uri. Once you get the UriInfo instance, we can get the query parameter as shown in
the above code at line 23.

Leave a Reply