JAX-RS @PathParam example

In this article we will explain in JAX-RS, you can use @PathParam to inject the value of URI parameter that defined in @Path expression, into Java method.

1. @PathParam – Single Parameter

A simple and normal way to use @PathParam.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
 
@Path("/employees")
public class EmployeeRestService {
 
 @GET
 @Path("{employeeId}")
 public Response getEmployeeById(@PathParam("employeeId") String employeeId) {
 
    return Response.status(200).entity("getEmployeeById is called, employeeId : " + employeeId).build();
 
 }
 
}

In above example, the value of {employeeId} from “/employees/{employeeId}” will match to “@PathParam(“employeeId”) String var“.

URI Pattern : “/employees/12121″

getEmployeeById is called, employeeId : 12121

2. @PathParam – Multiple Parameters

Example to inject multiple parameters into Java method.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
 
@Path("/employees")
public class EmployeeRestService {
 
 @GET
 @Path("{year}/{month}/{day}")
 public Response getEmployeeHistory(
   @PathParam("year") int year,
   @PathParam("month") int month, 
   @PathParam("day") int day) {
 
    String date = year + "/" + month + "/" + day;
 
    return Response.status(200)
  .entity("getEmployeeHistory is called, year/month/day : " + date)
  .build();
 
 }
 
}

URI Pattern : “/employees/2013/06/16”

getEmployeeHistory is called, year/month/day : 2013/06/16

Download SourceCode
JAX-RS @Path URI matching example.zip

References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next