JAX-RS @PathParam Example

In JAX-RS @Path is used on method level to determinate the URI path to which the method responds.@PathParam is used to retrieve the value of an URI path variable. In other words you can use @PathParem to inject the value of URI parameter that defined in @Path expression, into method input parameters.

In this example, we will see how to use @PathParam in method arguments of a JAX-RS RESTful webservices.


1. Technologies used

  • Maven
  • Jersey 1.9
  • Tomcat 6.0
  • Eclipse Juno
  • JDK 1.7

In JAX-RS @Path is used on method level to determinate the URI path to which the method responds.@PathParam is used to retrieve the value of an URI path variable. In other words you can use @PathParem to inject the value of URI parameter that defined in @Path expression, into Java method.

In this example, we will see how to use @PathParam in method arguments of a JAX-RS RESTful webservices.


1. Technologies used

  • Maven
  • Jersey 1.9
  • Tomcat 6.0
  • Eclipse Juno
  • JDK 1.7



Follow the steps mentioned below to develop the project.


Step 1 : Create Web Application Project using Maven Template

Create a Java web application project from maven-archetype-webapp template.

mvn archetype:generate -DgroupId=com.jwt.rest -DartifactId=RESTPathParamDemo -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false


Step 2 : Eclipse IDE integration

Convert this project to Eclipse web project with Maven command "mvn eclipse:eclipse -Dwtpversion=1.5".Open command prompt and navigate to generated "RESTPathParamDemo" project and issue following command.

mvn eclipse:eclipse -Dwtpversion=1.5


Step 3 : Import the Project into eclipse

Import the project into eclipse IDE.


Step 4 : Update pom.xml file

Add the jersey dependencies in pom.xml.

pom.xml

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.jwt.rest</groupId>
	<artifactId>RESTPathParamDemo</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>RESTPathParamDemo Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>

		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-server</artifactId>
			<version>1.9</version>
		</dependency>

		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-servlet</artifactId>
			<version>1.19</version>
		</dependency>

		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>jsr311-api</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-client</artifactId>
			<version>1.9</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>RESTPathParamDemo</finalName>
	</build>
</project>


After updating the pom.xml again execute "mvn eclipse:eclipse -Dwtpversion=1.5". After executing this command Maven will download required libraries.

Note:- After above step refresh your project otherwise eclipse will not recognize the downloaded files.


Step 5 : Create Java directory :

Create a directory named java under main."/src/main". Right click on the project then select New ->Folder and provide the name as "java" as shown below.


JAX-RS example

Now add this directory to class path of your project.


Step 6 : Add java directory to classpath of the Project :

  • Right click on Project -> Build Path -> Configure build path , a new screen will open in that screen click on Source tab and then click on Add folder as shown bellow.

  • JAX-RS example


  • Again one new screen will open and in that screen select the java checkbox and click on OK button as shown bellow.

  • JAX-RS example

    Now Java folder is in classpath of your project.



Step 7 : Create Web.xml configuration File

Specify Jersey framework Servlet for our application in web.xml file.In web.xml, register "com.sun.jersey.spi.container.servlet.ServletContainer", and puts your Jersey service folder under "init-param","com.sun.jersey.config.property.packages".

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>RESTfulExample</display-name>
 <servlet>
		<servlet-name>jersey-serlvet</servlet-name>
		<servlet-class>
                     com.sun.jersey.spi.container.servlet.ServletContainer
                </servlet-class>
		<init-param>
		     <param-name>com.sun.jersey.config.property.packages</param-name>
		     <param-value>com.jwt.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>


As you can see our servlet is mapped to /rest/ URI pattern. So the basic structure of the URIs used in this example will have the form :

http://localhost:8080/RESTPathParamDemo/rest/....


1 . Using @PathParam with single parameter

We will use @PathParam to parse a single URI parameter and retrieve the value of the name variable and set it into the name argument.

CompanyService.java

package com.jwt.rest;

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

@Path("/users")
public class UserRestService {
 
    // Single Parameter
    @GET
    @Path("{name}")
    public Response getUserByName(@PathParam("name") String name) {
        return Response.status(200).entity("getUserByName() method called, user name returned is  " + name + "]").build();
    }
 
}


In the above class ,Using @Path("{name}") we defined a new path parameter with name "name". After that we used @PathParam("name") to parse the value and push it to String "name" argument.


Run the application :

Right click on project -> run as -> run on server Select Apache tomcat and click on finish.


Access your page by typing following URL

http://localhost:8080/RESTPathParamDemo/rest/users/mukesh


Output :

JAX-RS example



2 . Using @PathParam with multiple parameters

Below is example to inject multiple parameters into Java method.


package com.jwt.rest;

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}/{branch}/{department}")
	public Response getEmployeeList(@PathParam("empID") String empID,
			@PathParam("branch") String branchName,
			@PathParam("department") String deptName) {

		String resp = "Employee ID is  " + empID
				+ " department is " + deptName + " and Branch name is " +branchName;
		return Response.status(200).entity(resp).build();
	}
}


Now access the page by typing following URL

http://localhost:8080/RESTPathParamDemo/rest/employee/102/chennai/manufacturing


Output :

JAX-RS example





References :- JAX-RS @PathParam JavaDoc



Related Articles

  1. Maven Overview


comments powered by Disqus