RestEasy: JAX-RS 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

JBoss RestEasy is a JAX-RS implementation for developing Restful web service in java. Once developed, it isn’t restricted to deploy only in JBoss Application Server but you can deploy in any other server like Apache Tomcat, Glassfish, Oracle Weblogic, etc

Annotation Used

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

Technology Used

  • Java 1.7
  • Eclipse Luna IDE
  • RestEasy-3.0.8.Final
  • Apache Maven 3.2.1
  • Apache Tomcat 7.0.54

Mavenize or download required jars

Add RestEasy-3.0.8.Final dependencies to pom.xml

	<properties>
		<resteasy.version>3.0.8.Final</resteasy.version>
		<resteasy.scope>compile</resteasy.scope> <!-- compile(Tomcat) / provided(JBoss) -->
		<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>
		<!-- RESTEasy JAX RS Implementation -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxrs</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- Resteasy Servlet Container Initializer -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-servlet-initializer</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- RESTEasy JAX RS Client -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-client</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.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_RestEasy-PathParam_Project_Structure_In_Eclipse

Jars Libraries Used in the Project (Maven Dependencies)

2_RestEasy-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 RestEasy 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.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher with servlet container
  • http requests with URL pattern “/resteasy/*” will be sent to the registered servlet called “javax.ws.rs.core.Application” i.e.; HttpServletDispatcher (org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher)
  • set resteasy.servlet.mapping.prefix as <context-param>, if your servlet-mapping has a url-pattern anything other than “/*”. In this example, set “/resteasy”
  • if not set, then you will end up with 404 not found error
  • set resteasy.resources as <param-name> with comma delimited list of fully qualified JAX-RS resource class names you want to register as <param-value> using global <context-param>
  • <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>RestEasy-PathParam</display-name>

	<!-- RestEasy resource registering -->
	<context-param>
		<param-name>resteasy.resources</param-name>
		<param-value>com.resteasy.series.pathparam.CustomerServiceImpl</param-value>
	</context-param>

	<!-- RestEasy Servlet -->
	<servlet>
		<servlet-name>javax.ws.rs.core.Application</servlet-name>
		<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>javax.ws.rs.core.Application</servlet-name>
		<url-pattern>/resteasy/*</url-pattern>
	</servlet-mapping>

	<!-- this is mandatory, if url-pattern is other than /* -->
	<context-param>
		<param-name>resteasy.servlet.mapping.prefix</param-name>
		<param-value>/resteasy</param-value>
	</context-param>

	<!-- 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 7.0 server so our server and port are localhost and 8080 respectively. Context root is the project name i.e.; RestEasy-PathParam. Initial path for this application is http://localhost:8080/RestEasy-PathParam

We have configured “/resteasy/*” as url-pattern for the “javax.ws.rs.core.Application” servlet in web.xml and at interface-level (or say class-level) path configured is “/customer” using @Path annotation. Next respective path for each method annotated with @Path (method-level)

Customer Service interface

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

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

ICustomerService.java

package com.resteasy.series.pathparam;

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

@Path("/customer")
public interface ICustomerService {

	// http://localhost:8080/RestEasy-PathParam/resteasy/customer/welcome/Harry - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-PathParam/resteasy/customer/welcome/Yuvan - JBoss AS7
	@GET
	@Path("/welcome/{custname}")
	public Response welcomeCustomer(@PathParam("custname") String userName);

	// http://localhost:8080/RestEasy-PathParam/resteasy/customer/custinfo/10001/chris/29  - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-PathParam/resteasy/customer/custinfo/10002/clarke/34 - JBoss AS7
	@GET
	@Path("/custinfo/{id}/{name}/{age}")
	public Response printCustomerInfo(
			@PathParam("id") String custId,
			@PathParam("name") String custName,
			@PathParam("age") String custAge);
}

Customer Service implementation

Implements above interface returning Response object for both methods

CustomerServiceImpl.java

package com.resteasy.series.pathparam;

import javax.ws.rs.core.Response;

public class CustomerServiceImpl implements ICustomerService {

	@Override
	public Response welcomeCustomer(String userName) {

		String welcomeMsg = "Welcome " + userName;
		return Response.status(200).entity(welcomeMsg).build();
	}

	@Override
	public Response printCustomerInfo(String custId, String custName, String custAge) {

		String customerInfo = "Customer [Id=" + custId +  ", Name=" + custName + ", Age=" + custAge + "]";
		return Response.status(200).entity(customerInfo).build();
	}
}

 

Deployment

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

Test the service !!

 

Testing

There are many ways to do testing

  • 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
  • Using ResteasyClient, ResteasyWebTarget and Response classes from JBoss package org.jboss.resteasy.client
  • Using ClientRequest and ClientResponse classes from JBoss package org.jboss.resteasy.client

 

1. Hit the web browser with GET URL

First Method:
Enter URL http://localhost:8080/RestEasy-PathParam/resteasy/customer/welcome/Harry

3_RestEasy_PathParam_first_method_browser

Second Method:
Enter URL http://localhost:8080/RestEasy-PathParam/resteasy/customer/custinfo/10001/chris/29

4_RestEasy_PathParam_second_method_browser

 

2. Using Advanced Rest client from Google Chrome

First Method:
Enter URL http://localhost:8080/RestEasy-PathParam/resteasy/customer/welcome/Harry

5_RestEasy_PathParam_first_method_advanced_rest_client

Second Method:
Enter URL http://localhost:8080/RestEasy-PathParam/resteasy/customer/custinfo/10001/chris/29

6_RestEasy_PathParam_second_method_advanced_rest_client

 

3. Java client (RestEasy)

There are two test clients which comes from JBoss RestEasy package org.jboss.resteasy.client and org.jboss.resteasy.client.jaxrs

  1. ClientRequest and ClientResponse for single parameter invocation
  2. ResteasyClient, ResteasyClientBuilder and ResteasyWebTarget for multiple parameter invocation

Note: above clients can be interchanged. No restriction, only needs to set correct http request parameters

TestCustomerService.java

package test.resteasy.series.pathparam;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

public class TestCustomerService {

	public static void main(String[] args) throws Exception {

		// setting & invoking first request
		System.out.println("Executing first service with single parameter");
		String url = "http://localhost:8080/RestEasy-PathParam/resteasy/customer/welcome/Yuvan";
		String responseString = testCustomerServiceForSingleParameter(url);
		System.out.println("Response String for First Service : " + responseString);

		// setting & invoking second request
		System.out.println("\n\nExecuting second service with multiple parameter");
		String url3 = "http://localhost:8080/RestEasy-PathParam/resteasy/customer/custinfo/10002/clarke/34";
		String responseString3 = testCustomerServiceWithMultipleParameters(url3);
		System.out.println("Response String for Second Service : " + responseString3);
	}

	/**
	 * using ClientRequest and ClientResponse classes from  org.jboss.resteasy.client
	 * @param url
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static String testCustomerServiceForSingleParameter(String url) throws Exception {

		// local variables
		ClientRequest clientRequest = null;
		ClientResponse<String> clientResponse = null;
		int responseCode;
		String responseString = null;

		try{
			clientRequest = new ClientRequest(url);
			clientRequest.setHttpMethod(HttpMethod.GET);
			clientRequest.accept(MediaType.APPLICATION_FORM_URLENCODED);
			clientResponse = clientRequest.get(String.class);

			responseCode = clientResponse.getResponseStatus().getStatusCode();
			System.out.println("Response code: " + responseCode);

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

			System.out.println("ResponseMessageFromServer: " + clientResponse.getResponseStatus().getReasonPhrase());
			responseString = clientResponse.getEntity();
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
		finally{
			// release resources, if any
			clientResponse.close();
			clientRequest.clear();
		}
		return responseString;
	}

	/**
	 * using ResteasyClient, ResteasyWebTarget and Response classes from org.jboss.resteasy.client
	 * @param url
	 */
	public static String testCustomerServiceWithMultipleParameters(String url) {

		// local variables
		ResteasyClient resteasyClient = null;
		ResteasyWebTarget resteasyWebTarget = null;
		Response response = null;
		int responseCode;
		String responseString = null;

		try{
			resteasyClient = new ResteasyClientBuilder().build();
			resteasyWebTarget = resteasyClient.target(url);
			response = resteasyWebTarget.request().get();

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

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

			System.out.println("ResponseMessageFromServer: " + response.getStatusInfo().getReasonPhrase());
			responseString = response.readEntity(String.class);

		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		finally{
			// release resources, if any
			response.close();
		}
		return responseString;
	}
}

Output in console

Executing first service with single parameter
Response code: 200
ResponseMessageFromServer: OK
Response String for First Service : Welcome Yuvan


Executing second service with multiple parameter
Response code: 200
ResponseMessageFromServer: OK
Response String for Second Service : Customer [Id=10002, Name=clarke, Age=34]

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

RestEasy-@PathParam-annotation (Tomcat server) (9kB)

Happy Coding !!
Happy Learning !!

RestEasy: JAX-RS web service using @PathParam annotation + JBoss AS7
RestEasy-3.0.x.Final - A JAX-RS specification to implement RestFul web services