JAX-RS @PathParam with example


What is PathParam ?

It is the annotation defined in JAX-RS specification which is used to resolve the values passed in the URL and inject them to the method.

Values are passed in the URL with @Path expression.

@Path expression is just the parameters which are enclosed in curly braces in URL.

This annotation will be used at the method argument level.

Example:

http://sample.com/user/{id}

Here “id” is passed as part of the URL with @Path expression.
and hence “id” is a path parameter in this URL.

For the above example, we can use @PathParam in method argument as below

(@PathParam(“id”) String id)

http://sample.com/{name}/{age}/user/

Here “name” and “age” are passed as part of the URL with @Path expression.
and hence “name” and “age” are the path parameters in this URL.

For the above example, we can use @PathParam in method argument as below

(@PathParam(“name”) String name, @PathParam(“age”) String age)

Let’s see the complete example on this

Create a new Maven Web project in eclipse (Refer Rest service Hello World project for the same)

Project structure

path_param_proj_structure

Step 1

Update pom.xml with below dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4.         http://maven.apache.org/maven-v4_0_0.xsd">
  5.   <modelVersion>4.0.0</modelVersion>
  6.   <groupId>PathParam</groupId>
  7.   <artifactId>PathParam</artifactId>
  8.   <packaging>war</packaging>
  9.   <version>0.0.1-SNAPSHOT</version>
  10.   <name>PathParam Maven Webapp</name>
  11.   <url>http://maven.apache.org</url>
  12.   <dependencies>
  13.     <dependency>
  14.       <groupId>junit</groupId>
  15.       <artifactId>junit</artifactId>
  16.       <version>3.8.1</version>
  17.       <scope>test</scope>
  18.     </dependency>
  19.      <dependency>
  20.     <groupId>org.glassfish.jersey.containers</groupId>
  21.     <artifactId>jersey-container-servlet</artifactId>
  22.     <version>2.24</version>
  23. </dependency>
  24.   </dependencies>
  25.   <build>
  26.     <finalName>PathParam</finalName>
  27.   </build>
  28. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>PathParam</groupId>
  <artifactId>PathParam</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>PathParam Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.24</version>
</dependency>
  </dependencies>
  <build>
    <finalName>PathParam</finalName>
  </build>
</project>

We have added dependencies for Jersey servlet and Junit in the above pom file.

Step 2

Update web.xml file with Jersey servlet container

  1. <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  2.                          "http://java.sun.com/dtd/web-app_2_3.dtd" >
  3.  
  4. <web-app>
  5.   <display-name>Archetype Created Web Application</display-name>
  6.   <servlet>
  7.         <servlet-name>jersey-serlvet</servlet-name>
  8.          <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  9.         <init-param>
  10.             <param-name>jersey.config.server.provider.packages</param-name>
  11.             <param-value>com.kb.rest</param-value>
  12.         </init-param>
  13.         <load-on-startup>1</load-on-startup>
  14.     </servlet>
  15.  
  16.     <servlet-mapping>
  17.         <servlet-name>jersey-serlvet</servlet-name>
  18.         <url-pattern>/rest/*</url-pattern>
  19.     </servlet-mapping>
  20. </web-app>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
                         "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
		<servlet-name>jersey-serlvet</servlet-name>
		 <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 
		<init-param>
			<param-name>jersey.config.server.provider.packages</param-name>
			<param-value>com.kb.rest</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>jersey-serlvet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
</web-app>

we have defined a special servlet called “jersey-serlvet” in web.xml and mapped it by the URL pattern /rest/*
Any request matching the above pattern will be handled by jersey Servlet.

Step 3

Create PathParamUserService as below

  1. package com.kb.rest;
  2.  
  3. import javax.ws.rs.GET;
  4. import javax.ws.rs.POST;
  5. import javax.ws.rs.Path;
  6. import javax.ws.rs.PathParam;
  7. import javax.ws.rs.Produces;
  8. import javax.ws.rs.core.Response;
  9.  
  10. @Path("/user")
  11. public class PathParamUserService {
  12.    
  13.     @GET
  14.     @Path("{id}")
  15.     @Produces("text/html")
  16.     public Response getUserDetails(@PathParam("id") String id){
  17.            
  18.         //Service call to Get user Data based on id from DB
  19.         String output ="user details for id "+id+ ": Name:John, state : New jersey,Country:USA, age:45";
  20.        
  21.         return Response.status(200).entity(output).build();
  22.     }
  23.  
  24.     @GET
  25.     @Path("{name}/{state}")
  26.     @Produces("text/html")
  27.     public Response getUserByNameAndState(@PathParam("name") String name,
  28.                                            @PathParam("state") String state){
  29.            
  30.         //Service call to Get user Data based on name and state from DB
  31.         String output ="user details : Name:John, state : New jersey,Country:USA, age:45";
  32.        
  33.         return Response.status(200).entity(output).build();
  34.     }
  35. }
package com.kb.rest;

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

@Path("/user")
public class PathParamUserService {
	
	@GET
	@Path("{id}")
	@Produces("text/html")
	public Response getUserDetails(@PathParam("id") String id){
			
		//Service call to Get user Data based on id from DB
		String output ="user details for id "+id+ ": Name:John, state : New jersey,Country:USA, age:45";
		
        return Response.status(200).entity(output).build();
	}

	@GET
	@Path("{name}/{state}")
	@Produces("text/html")
	public Response getUserByNameAndState(@PathParam("name") String name,
                                           @PathParam("state") String state){
			
		//Service call to Get user Data based on name and state from DB
		String output ="user details : Name:John, state : New jersey,Country:USA, age:45";
		
        return Response.status(200).entity(output).build();
	}
} 

In this service, we have written 2 methods, one will get the user details based on “id” and other will get the user details based on “name” and “state”

In the first method,
We are passing “id” as a path param and retrieving it in the method.

In the second method,
We are passing name and state to get the user details

Above services can be accessed with the url as below

http://localhost:8080/PathParam/rest/user/1
This URL is mapped to first method in the Rest service as one value is passed in the URL after /user which is 1

http://localhost:8080/PathParam/rest/user/John/NewJersey
This URL is mapped to second method in the Rest service as 2 values are passed in the URL after /user which are John and NewJersey

Please find the below diagram for the association of Path param with method arguments.

After @Path, first curly brace is correpsnding to first parameter in the URL which is name and second curly brace is corresponding to second parameter in the URL which is state.

Path param explanation

Step 4

Build and deploy the project

Step 5

Let’s see the output

Access below URL
http://localhost:8080/PathParam/rest/user/1

Path_param_output1

Access below URL
http://localhost:8080/PathParam/rest/user/John/NewJersey

output_2

We can see that our output has retrieved user details based on parameters passed in the path.

Download this project JAXRSPathParam.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on