Retrieving url template parameters in JAX-RS annotated method

In JAX-RS, we can create url templates in the format as shown below


where anything between ‘{‘ and ‘}’ acts as places where we can provide parameters when creating the actual url.

The name between ‘{‘ and ‘}’ in url template will act as the parameter name.

In the actual url the text {parameter_name} is replaced by the value as shown below


where id is replaced by value 20. Now the value of parameter id will be 20.

In the JAX-RS annotated method we retrieve the value by using the parameter name as shown below

Main Code

1  package resource;
3  import;
4  import;
5  import;
6  import;
7  import;
8  import;
9  import;
11 @Path("webresource4")
12 public class WebResource4 {
13  @GET
14  @Path("retrieveRecord1/{id}")
15  public Response retrieveRecord1(@PathParam("id") String id) {
16      Response response = Response.ok("Retrieving record: " + id, MediaType.TEXT_PLAIN).build();
17      return response;
18  }
20  @GET
21  @Path("retrieveRecord2/{id}")
22  public Response retrieveRecord2(@Context UriInfo info) {
23      String id = info.getPathParameters().getFirst("id");
24      Response response = Response.ok("Retrieving record: " + id, MediaType.TEXT_PLAIN).build();
25      return response;
26  }
27 }

At line 14 and 21, we create part of the url template “retrieveRecord1/{id}” and “retrieveRecord2/{id}” and provide as parameter to @Path annotation.

Together with @Path at class level and servlet context the following url templates are created

In the first method retrieveRecord1, I create a method parameter “id” and annotate with @PathParam and provide the parameter name which is similar to parameter name in url template.

In this way I am telling JAX-RS runtime to retrieve the value provided in place of parameter named “id” from the actual url and inject it to String variable id.

In the second method retrieveRecord2, I am telling JAX-RS runtime to inject context information UriInfo instance to method parameter info.

From UriInfo instance we retrieve the parameter value as shown in line 23.

For example if the above resource is accessed using the actual url, the output will be

Output –> Retrieving record: 20


Output –> Retrieving record: 10

Leave a Reply