JAX-RS @PathParam Example

The JAX-RS @PathParam annotation allows you to inject the value of named URI path parameters that were defined in the @Path annotation expression. In this example we’ll explore the different ways you can use the @PathParam and look at how you can retrieve these path parameters programatically.

Mapping Path Parameters

The path parameter defined in the @Path expression can be injected via the @PathParam annotation. The type conversions happens automatically if the provided type maps the supplied value.

package com.memorynotfound.rs;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/customers")
public class CustomerResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getCustomerById(@PathParam("id") int id){
        return Response
                .ok()
                .entity("customer with id: " + id)
                .build();
    }


}

When we use the following HTTP request: /customers/1 we receive the following response:

customer with id: 1

Passing Multiple Path Parameters

You can register multiple path parameters in you Java methods.

Multiple @PathParam’s in each URI Segment

You can have multiple @PathParam annotations which all map to their own unique parameter provided in the @Path annotation. In this example every path parameter is registered in it’s own URI Segment.

package com.memorynotfound.rs;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/cars")
public class CarResource {

    @GET
    @Path("{brand}/{model}/{year}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getCar(@PathParam("brand") String brand,
                           @PathParam("model") String model,
                           @PathParam("year") Integer year){

        return Response
                .ok()
                .entity("getCar with brand: " + brand +
                        ", model: " + model +
                        ", year: " + year)
                .build();
    }

}

When we use the following HTTP request: /cars/bmw/x1/2016 we receive the following response:

getCar with brand: bmw, model: x1, year: 2016

Multiple @PathParam’s in one URI Segment

You can also have multiple path parameters in the same URI Segment. Here is an example.

package com.memorynotfound.rs;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

@Path("/orders")
public class OrderResource {

    @GET
    @Path("{day}-{month}-{year}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getOrder(@PathParam("day") Integer day,
                             @PathParam("month") Integer month,
                             @PathParam("year") Integer year){

        return Response
                .ok()
                .entity("getOrder with day: " + day +
                        ", month: " + month +
                        ", year: " + year)
                .build();
    }

}

When we use the following HTTP request: /orders/01-01-2015 we receive the following response:

getOrder with day: 1, month: 1, year: 2015

Getting Path Parameters Programatically

You can retrieve path information using the UriInfo class. The UriInfo#getPathParameters() returns a map of all the path parameters defined for all matching @Path expressions.

package com.memorynotfound.rs;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

@Path("/products")
public class ProductResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getProduct(@Context UriInfo uriInfo){

        String id = uriInfo.getPathParameters().getFirst("id");

        for (String name : uriInfo.getPathParameters().keySet()){
            System.out.println("path param name: " + name + " with value: " + uriInfo.getPathParameters().getFirst(name));
        }

        return Response
                .ok()
                .entity("getProduct with id: " + id)
                .build();
    }

}

When we use the following HTTP request: /products/1 we receive the following response:

getProduct with id: 1

Resolving Path Parameter Templates in JAX-RS Client

You can use path templates in the client URI and resolve these path templates using the WebTarget#resolveTemplate(name, value) method.

package com.memorynotfound.rs;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;

public class RunClient {

    public static void main(String... args){
        Client client = ClientBuilder.newClient();

        Response response = client
                .target("http://localhost:8081/jaxrs-pathparam/api/products/{id}")
                .resolveTemplate("id", 123)
                .request()
                .get();

        if (response.getStatus() == 200){
            System.out.println("Response: " + response.readEntity(String.class));
        }
        client.close();
    }
}

References

Download

You may also like...