Jersey 2.x web service using @PathParam annotation

In this article, we will learn and implement @PathParam annotation in JAX-RS Restful web service. Using @PathParam, you can map/bind values of the URL parameter with formal arguments of the Java method

Jersey is the most popular amongst Restful web service development. Latest Jersey 2.x version has been developed by Oracle/Glassfish team in accordance with JAX-RS 2.0 specification. Earlier Jersey 1.x version was developed and supported by Oracle/Sun team

Latest Jersey release version is 2.12 see here and look documentation and API for details. We will implement Jersey examples in the following articles based on latest 2.x version

Annotation Used

  • @PathParam (ws.rs.PathParam)
  • @Path (ws.rs.Path)
  • @GET (ws.rs.GET)

Technology Used

  • Java 1.7
  • Eclipse Luna IDE
  • Jersey-2.12
  • Apache Maven 3.2.1
  • Apache Tomcat 8.0.54
  • Glassfish-4.1

Mavenize or download required jars

Add Jersey-2.12 dependencies to pom.xml

	<properties>
		<jersey.version>2.12</jersey.version>
		<jersey.scope>compile</jersey.scope>
		<compileSource>1.7</compileSource>
		<maven.compiler.target>1.7</maven.compiler.target>
		<maven.compiler.source>1.7</maven.compiler.source>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<!-- Jersey core Servlet 2.x implementation -->
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet-core</artifactId>
			<version>${jersey.version}</version>
			<scope>${jersey.scope}</scope>
		</dependency>
	</dependencies>

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the central repository or maven repository and include them in the classpath

Directory Structure

Before moving on, let us understand the directory/package structure once you create project in Eclipse IDE

Maven has to follow certain directory structure

  • src/test/java –> test related files, mostly JUnit test cases
  • src/main/java –> create java source files under this folder
  • src/main/resources –> all configuration files placed here
  • src/test/resources –> all test related configuration files placed here
  • Maven Dependencies or Referenced Libraries –> includes jars in the classpath
  • WEB-INF under webapp –> stores web.xml & other configuration files related to web application

Project Structure (Package Explorer view in Eclipse)

1_Jersey-PathParam_Project_Structure_In_Eclipse

Jars Libraries Used in the Project (Maven Dependencies)

2_Jersey-PathParam_Jars_In_Classpath

Web application

For any web application, entry point is web.xml which describes how the incoming http requests are served / processed. Further, it describes about the global-context and local-context param (i.e.; <context-param> & <init-param>) for loading files particular to project requirements & contains respective listener

With this introduction, we will understand how we configured web.xml for Jersey JAX-RS Restful web service

web.xml (the entry point –> under WEB-INF)

This web.xml file describes,

  • Like any JEE web framework register “org.glassfish.jersey.servlet.ServletContainer” with servlet container
  • http requests with URL pattern “/rest/*” will be sent to the registered servlet called “jersey-servlet” i.e.; (org.glassfish.jersey.servlet.ServletContainer)
  • Set <init-param> with <param-name> as “jersey.config.server.provider.packages” and <param-value> describing the qualified package name of the JAX-RS annotated Resource/Provider classes. In this example, “com.jersey.series.pathparam
  • <welcome-file-list> files under this tag is the start-up page

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

	<display-name>Jersey-PathParam</display-name>

	<!-- Jersey Servlet -->
	<servlet>
		<servlet-name>jersey-servlet</servlet-name>
		<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
		<!-- Register resources and providers -->
		<init-param>
			<param-name>jersey.config.server.provider.packages</param-name>
			<param-value>com.jersey.series.pathparam</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

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

	<!-- welcome file -->
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>

Let’s see coding in action

 

URL Pattern

Http url for any common web application is http://<server>:<port>/<root-context>/<from_here_application_specific_path>

In our example, we are going to deploy the war into Tomcat 8.0 server so our server and port are localhost and 8080 respectively. Context root is the project name i.e.; Jersey-PathParam. Initial path for this application is http://localhost:8080/Jersey-PathParam

We have configured “/rest/*” as url-pattern for the “jersey-servlet” servlet in web.xml and at class-level path configured is “/bookservice” using @Path annotation. Next respective path for each method annotated with @Path (method-level)

Book Service interface

Defines two simple abstract methods

  • First one takes 1-argument
  • Second takes 3-arg arguments

NOTE: It’s always a good programming practice to do code-to-interface and have its implementation separately

IBookService.java

package com.jersey.series.pathparam;

import javax.ws.rs.core.Response;

public interface IBookService {

	public Response printBookName(String bookName);
	public Response printCompleteBookDetails(String bookName, String author, String category);
}

Book Service implementation

Implements above interface returning Response object for both methods

Using @PathParam, value of the URL parameter are mapped into formal arguments of the Java methods

Concrete implementation for above two simple methods

Note: Jersey doesn’t inherit JAX-RS annotations. So we are annotating Resource/Provider classes and then defining qualified package name in web.xml

BookServiceImpl.java

package com.jersey.series.pathparam;

import javax.ws.rs.Consumes;
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;

@Path("bookservice")
public class BookServiceImpl implements IBookService {

	// http://localhost:8080/Jersey-PathParam/rest/bookservice/book/LifeSciences
	@GET
	@Path("book/{name}")
	@Consumes({MediaType.TEXT_PLAIN})
	@Produces({MediaType.TEXT_PLAIN})
	public Response printBookName(@PathParam("name") String bookName) {

		String bookDetail = "Book name is " + bookName;
		return Response.status(200).entity(bookDetail).build();
	}

	// http://localhost:8080/Jersey-PathParam/rest/bookservice/bookdetail/Enzymology/Devasena/Biochemistry
	@GET
	@Path("bookdetail/{name}/{author}/{category}")
	@Consumes({MediaType.TEXT_PLAIN})
	@Produces({MediaType.TEXT_PLAIN})
	public Response printCompleteBookDetails(
			@PathParam("name") String bookName,
			@PathParam("author") String author,
			@PathParam("category") String category) {

		String bookCompleteDetail = "Book complete detail [Name=" + bookName +  ", Author=" + author + ", Category=" + category + "]";
		return Response.status(200).entity(bookCompleteDetail).build();
	}
}

 

Tomcat-8.0.12 Deployment

  • Run maven command to build the war: mvn clean install (use command prompt or integrated maven in eclipse IDE
  • Copy(ctrl+c) the war file from the target folder
  • Paste(ctrl+v) it into apache tomcat (webapps folder)
  • Start the tomcat server

 

Glassfish-4.1 Deployment

  • Run maven command to build the war: mvn clean install (use command prompt or integrated maven in eclipse IDE
  • Once you see “BUILD SUCCESS” after running maven command, keep the war file ready to be deployed
  • There are two ways to deploy war file into Glassfish-4.1
    1. Online
    2. Offline
  • Click here to understand above deployments process in detail

Test the service !!

Testing

There are many ways to do testing

  • Access html page from web browser
  • Copy the URL of GET service into web browser
  • Advanced REST client from Google Chrome
  • Rest client in Mozilla Firefox Add On
  • Write your own client for example, Java client using improved CloseableHttpClient from Apache
  • JDK’s in-built classes like HttpURLConnection
  • Using Client, WebTarget from core JAX-RS classes javax.ws.rs.client

 

1. Hit the web browser with GET URL

First Method:
Enter url http://localhost:8080/Jersey-PathParam/rest/bookservice/book/LifeSciences
3_Jersey_PathParam_first_method_browser

Second Method:
Enter url http://localhost:8080/Jersey-PathParam/rest/bookservice/bookdetail/Enzymology/Devasena/Biochemistry
4_Jersey_PathParam_second_method_browser

 

2. Using Advanced Rest client from Google Chrome

First Method:
Enter url http://localhost:8080/Jersey-PathParam/rest/bookservice/book/LifeSciences
5_Jersey_PathParam_first_method_advanced_rest_client

Second Method:
Enter url http://localhost:8080/Jersey-PathParam/rest/bookservice/bookdetail/Enzymology/Devasena/Biochemistry
6_Jersey_PathParam_second_method_advanced_rest_client

 

3. Java client

Uses Client, ClientBuilder, WebTarget and Response classes from core JAX-RS package javax.ws.rs.client for invoking Restful web service

Note: Commented lines will help out us to various request header parameters

TestBookService.java

package test.jersey.series.pathparam;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.ClientConfig;

public class TestBookService {

	public static void main(String[] args) {

		// setting & invoking first request
		System.out.println("Executing first service with single parameter");
		String httpURL = "http://localhost:8080/Jersey-PathParam/rest/bookservice/book/LifeSciences";
		String responseString = testBookService(httpURL);
		System.out.println("responseString : " + responseString);

		// setting & invoking second request
		System.out.println("\n\nExecuting second service with multiple parameter");
		String httpURL3 = "http://localhost:8080/Jersey-PathParam/rest/bookservice/bookdetail/Enzymology/Devasena/Biochemistry";
		String responseString3 = testBookService(httpURL3);
		System.out.println("responseString : " + responseString3);
	}

	public static String testBookService(String httpURL) {

		// local variables
		ClientConfig clientConfig = null;
		Client client = null;
		WebTarget webTarget = null;
		Builder builder = null;
		Response response = null;
		int responseCode;
		String responseMessageFromServer = null;
		String responseString = null;

		try{
			// invoke service after setting necessary parameters
			clientConfig = new ClientConfig();
			client =  ClientBuilder.newClient(clientConfig);
			//			client.property("Content-Type", MediaType.TEXT_PLAIN);
			//			client.property("accept", MediaType.TEXT_PLAIN);
			webTarget = client.target(httpURL);

			// invoke service
			builder = webTarget.request(MediaType.TEXT_PLAIN).accept(MediaType.TEXT_PLAIN);
			response = builder.get();

			// get response code
			responseCode = response.getStatus();
			System.out.println("Response code: " + responseCode);

			if (response.getStatus() != 200) {
				throw new RuntimeException("Failed with HTTP error code : " + responseCode);
			}

			// get response message
			responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
			System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

			// get response string
			responseString = response.readEntity(String.class);
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
		finally{
			// release resources, if any
			response.close();
			client.close();
		}
		return responseString;
	}
}

Output in console

Executing first service with single parameter
Response code: 200
ResponseMessageFromServer: OK
responseString : Book name is LifeSciences


Executing second service with multiple parameter
Response code: 200
ResponseMessageFromServer: OK
responseString : Book complete detail [Name=Enzymology, Author=Devasena, Category=Biochemistry]

Conclusion: With @PathParam annotation, you can retrieve URL parameter values appended at the end and map it to the corresponding formal arguments of the Java methods

Download project

Jersey-2x-PathParam (8kB)

Happy Coding !!
Happy Learning !!

Glassfish-4.1 Deployment process
Introduction to Jersey 2.x Restful web services