JAX-RS @PathParam annotation example
This page gives you an example using JAX-RS @PathParam annotation, which injects value from URI to your method input
parameters.
In the previous examples we have given details of application setup, dependencies, web.xml file configurations: If you want to
know about these configuration, please refer these:
Restful web services using RESTEasy hello world example.
Restful web services using Jersey hello world example.
Look at the below class to apply @PathParam annotation:
package com.java2novice.restful;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@Path("/employee")
public class EmployeeService {
@GET
@Path("{empId}")
public Response getEmployeeById(@PathParam("empId") String empId){
return Response.status(200).entity("Got employee with id : " + empId).build();
}
@GET
@Path("{branch}/{department}")
public Response getEmployeeList(@PathParam("branch") String branchName,
@PathParam("department") String deptName){
String resp = "Total number of employees in the "+deptName+" department from "
+branchName+" is 100";
return Response.status(200).entity(resp).build();
}
}
|
In the above example, if you use "/employee/123" URI pattern, getEmployeeById() method will be invoked, and you will get "Got employee with id : 123"
as a response.
Using @PathParam, you can access multiple values as well. Look at getEmployeeList() method in the above example, if you use
"/employee/bangalore/accounts" URI pattern, then getEmployeeByName() method will be invoked and you will get "Total number of employees in the accounts department from bangalore is 100"
as a response.
In the next page you will see an example on how to use @QueryParam annotation.
|