RESTful Web Services @PathParam Example using JAX-RS and Jersey

@PathParam Example

In this example we are going to develop a simple RESTful web service using JAX-RS and Jersey to extract path parameters from the request URL using the @PathParam annotation.

In this example we have developed a simple calculate rest service which calculates square root of a number by extracting the value from the path using @PathParam annotation. In addition, we have added both add and subtract methods that will accept multiple @PathParam parameters.

@PathParam can be used only on the following Java types:

  • All primitive types except char
  • All wrapper classes of primitive types except Character
  • Any class with a constructor that accepts a single Stringargument
  • Any class with the static method named valueOf(String) that accepts a single Stringargument
  • Any class with a constructor that takes a single String as a parameter

Getting Started

In order to run this tutorial yourself, you will need the following:

  • Java JDK 1.6 or greater
  • Favorite IDE Spring Tool Suite (STS), Eclipse IDE or NetBeans (I happen to be using STS because it comes with a Tomcat server built-in)
  • Tomcat 7 or greater or other popular container (Weblogic, Websphere, Glassfish, JBoss, VMWare vFabric, etc). For this tutorial I am using VMware vFabric tc Server Developer Edition which is essentially an enhanced Tomcat instance integrated with Spring STS
  • Jersey JAX-RS
  • log4J (for logging purposes)

Required Libraries

Copy all of the following jars to WebContent->WEB-INF->lib folder.

asm-3.1.jar
jersey-client-1.18.jar
jersey-core-1.18.jar
jersey-json-1.18.jar
jersey-server-1.18.jar
jersey-servlet-1.18.jar
jsr311-api-1.1.1.jar
log4j-1.2.17.jar

Complete Project Overview

I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

jax-rs pathparam proj

RESTful Web Service End Points

#URIMethodDescription
1/rest/calculate/squareroot/{value}GETCalculates the square root of a number denoted by value
2/rest/calculate/add/{value1}/{value2}GETAdds the numbers denoted by value1 and value2
2/rest/calculate/subtract/{value1}/{value2}GETSubtracts the numbers denoted by value1 and value2

Using the @PathParam in JAX-RS API

pathparam url structure

Single @PathParam Parameter

In this example we show you how to extract a single parameter from the request URL.

@GET
@Path("/squareroot/{value}")
@Produces(MediaType.TEXT_HTML)
public Response calcSqrt(@PathParam("value")  int value) {

  double answer = Math.sqrt(value);
  String msg = String.format("calcSqrt==> value: %d, answer: %10.4f", value, answer);
  logger.info(msg);
    
  return Response.status(200).entity(msg).build();
}

Multiple @PathParam Parameters

In this example we show you how to extract multiple parameters from the request URL.

@GET
@Path("/add/{value1}/{value2}")
@Produces(MediaType.TEXT_HTML)
public Response calcAddTwoValues(@PathParam("value1")  double value1, 
                                 @PathParam("value2")  double value2) {
  double answer = value1 + value2;
  String msg = String.format("calcAddTwoValues==> value1: %10.4f, value2: %10.4f, answer: %10.4f", 
                                                  value1, value2, answer);
  logger.info(msg);
    
  return Response.status(200).entity(msg).build();
}

Complete Program using @PathParam

package com.avaldes;

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;

import org.apache.log4j.Logger;

@Path("/calculate")
public class RestfulPathParamExample {
  static Logger logger = Logger.getLogger(RestfulPathParamExample.class);
  
  @GET
  @Path("/squareroot/{value}")
  @Produces(MediaType.TEXT_HTML)
  public Response calcSqrt(@PathParam("value")  int value) {

    double answer = Math.sqrt(value);
    String msg = String.format("calcSqrt==> value: %d, answer: %10.4f", value, answer);
    logger.info(msg);
    
    return Response.status(200).entity(msg).build();
  }
  
  @GET
  @Path("/add/{value1}/{value2}")
  @Produces(MediaType.TEXT_HTML)
  public Response calcAddTwoValues(@PathParam("value1")  double value1, 
                                   @PathParam("value2")  double value2) {

    double answer = value1 + value2;
    String msg = String.format("calcAddTwoValues==> value1: %10.4f, value2: %10.4f, answer: %10.4f", 
                  value1, value2, answer);
    logger.info(msg);
    
    return Response.status(200).entity(msg).build();
  }
  
  @GET
  @Path("/subtract/{value1}/{value2}")
  @Produces(MediaType.TEXT_HTML)
  public Response calcSubTwoValues(@PathParam("value1")  double value1, 
                                   @PathParam("value2")  double value2) {

    double answer = value1 - value2;
    String msg = String.format("calcSubTwoValues==> value1: %10.4f, value2: %10.4f, answer: %10.4f", 
                  value1, value2, answer);
    logger.info(msg);
    
    return Response.status(200).entity(msg).build();
  }
}

Web Deployment Descriptor (web.xml)

This is a pretty straight forward deployment descriptor file – only thing you need to add is the location of you java package in the Jersey ServletContainer entry as init-param. Please ensure you add it to the web.xml file as shown below.

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>com.omega.rest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
 
   <servlet-name>Jersey REST Service</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.avaldes</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

Testing out the Web Services

In this example, we calculate the square root of a number using the web service using a single @PathParam parameter.

pathparam sqrt

This next example, adds two numbers using the web service using multiple @PathParam parameters.

pathparam add

This last example, subtracts two numbers using the web service using multiple @PathParam parameters.

pathparam sub

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java jaxrs pathparam

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

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