JAX-RS: How to Get Values from @PathParam in Jersey

Connect with

JAX-RX path parameterJAX-RS path parameter using @PathParam annotaion for retrieving path param variables. In JAX-RS, binding of path variable in the controller/service method is very easy by using @PathParam annotation.

In the JAX-RS tutorial series for retrieving of value from path parameter using @pathParam annotatin.

1. Maven Dependency for JAX-RS path parameter example

You can choose version of jersey as per your choice for JAX-RS path parameter example. JAX-RS jersey is on of the choice for developing the rest API .


   com.sun.jersey
   jersey-server
   1.9

2. Binding with one path variable

In the JAX-RS tutorial series of jersey rest api, I tried to explain about how to retriev value of path parameter using @PathParam annotation.

package com.mysoftkey.jaxrs;

import java.util.HashMap;
import java.util.Map;

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;

/**
 * This service / controller class is used to get pathParam variable by using @PathParam annotation, 
 * in argument of method.
 * 
 * @author Ranjeet Jha
 *
 */
@Path("/pathParam")
public class PathParamService {

	/**
	 * In this method , retrieving path parameter from PathParam.
	 * 
	 * service end point:  http://localhost:8080/jersey/pathParam/1
	 * 
	 * @param userAgent
	 * @return
	 */
	@GET
	@Path("{id}")
	public Response getUserById(@PathParam("id") String id) {
 
	   return Response.status(200).entity("id : " + id).build();

	}
}

Service URL: http://localhost:8080/jersey/pathParam/1
output :

3. Binding With Multiple Path Variable

You can use @PathParam annotation for retriving value from path variable in jersey rest api

/**
 * In this method, retrieving path parameter from PathParam with multiple parameters.
 * 
 * service endpoint:  http://localhost:8080/jersey/pathParam/1/2
 * 
 * @return a JSON object with HTTP status code 200 ok
 */
@GET
@Path("{categoryId}/{productId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUserHistory(@PathParam("categoryId") int categoryId,
	@PathParam("productId") int productId) {
   
   Map map = new HashMap();
   map.put("categoryId", categoryId);
   map.put("productId", productId);
 return Response.status(200).entity(map).build();

}

Service URL: http://localhost:8080/jersey/pathParam/1/2
output :

{
categoryId: 1,
productId: 2
}

4. Download Source Code

Download source code of JAX-RS: Jersey PathParam Example

5. References

  1. Jersey Official site
  2. JAX-RS official site
  3. Oracle Java Web services tutorial
  4. Wikipedia

Connect with

Leave a Comment

Your email address will not be published. Required fields are marked *