×
☰ See All Chapters

PathParam Example

@PathParam allows the rest service consumer to pass the input in service URI. Each parameter should be separated by / (forward slash). In this tutorial you will learn to pass the input to rest service and extract the input parameters using @PathParam. Follow the below steps to create the example.

Step 1: Create a dynamic web project.

 pathparam-0
 

Step 2: Add Jersey implementation Jars by downloading from the following location.

(Google search key word “jax rs jersey jar download”)

https://jersey.github.io/download.html

Or click here to download the jars that we have used.

Now we will get jaxrs-ri-2.28.zip, extract the zip file. Copy all the jars present in lib, ext and api directories into “WebContent/WEB-INF/ lib” directory of project.

pathparam-1
 

Step 3: Now create a Restful services using PathParam annotations.

RestServicePathParam.java

package com.java4coding;

 

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;

@Path("/hello")

public class RestServicePathParam {

        @GET

        @Path("{firstName}/{lastName}")

        @Produces(MediaType.TEXT_PLAIN)

        public String sayHello(@PathParam("firstName") String firstName, @PathParam("lastName") String lastName) {

                return "Hello " + firstName+ " "+ lastName;

        }

}

Step 5: In web.xml, configure service as below.

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/j2ee" xmlns:web="https://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/j2ee https://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">

  <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.java4coding</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>

Final project directory structure is

pathparam-2
 

Step 5:  Deploy the project to any server (Let’s consider Tomcat), Just right click on the project >Run As > Run on Server >Select Tomcat server.

Open below URL in browser. (Change the project name and port number according to your setup)

https://localhost:8090/JAX_RS_PathParamAnnotationExample/rest/hello/Manu/Manjunatha

 

pathparam-3
 

All Chapters
Author