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;
2  
3  import javax.ws.rs.GET;
4  import javax.ws.rs.Path;
5  import javax.ws.rs.QueryParam;
6  import javax.ws.rs.core.Context;
7  import javax.ws.rs.core.MediaType;
8  import javax.ws.rs.core.Response;
9  import javax.ws.rs.core.UriInfo;
10 
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  }
19  
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
http://localhost:8080/JAXRSConcepts/myresources/webresource2/queryParameters1?param1=value1
http://localhost:8080/JAXRSConcepts/myresources/webresource2/queryParameters2?param1=value3

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s