RESTful Web Services (JAX-RS) @Path URI Matching Example

Any Java class that you want to be recognized as JAX-RS services must have @Path annotation.

In JAX-RS, @Path annotation is used to bind URI pattern to a Java method. Java Class annotated with @Path have at least one method annotated with @Path or a request method designator annotation such as @GET, @POST.

The @Path annotation must exist on either the class and/or a resource method. If it exists on both the class and method, the relative path to the resource method is a concatenation of the class and method.

Let us understand @Path annotation with an example.In this example, we will discuss how to use @Path annotation on class and resource methods.

Any Java class that you want to be recognized as JAX-RS services must have @Path annotation.

In JAX-RS, @Path annotation is used to bind URI pattern to a Java method. Java Class annotated with @Path have at least one method annotated with @Path or a request method designator annotation such as @GET, @POST.

The @Path annotation must exist on either the class and/or a resource method. If it exists on both the class and method, the relative path to the resource method is a concatenation of the class and method.

Let us understand @Path annotation with an example.In this example, we will discuss how to use @Path annotation on class and resource methods.





Technologies and Tools used

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

Follow the steps mentioned below to develop Hello World program using Jersey and JAX-RS web service.


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=RESTPathExample -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 "RESTPathExample" 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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.jwt.rest</groupId>
  <artifactId>RESTPathExample</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>RESTPathExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-server</artifactId>
			<version>1.17</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-servlet</artifactId>
			<version>1.17</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.17</version>
		</dependency>
  </dependencies>
  <build>
    <finalName>RESTPathExample</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.


After these steps your project directory should be same as screen shot given below.


Directory Structure :


JAX-RS example


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/RESTPathExample/rest/....

URIs in @Path are defined in two way:

  1. @Path ("uri")
  2. @Path ("uri/{variable[:regular-expression]}")

See following examples to show you how it works.


Normal URI matching:

Let us consider scenario of a company , company has employees and employee can be permanent and contract. You want to make an REST API that will return a list of all employee and then specifically the list of permanent and contract employee. Let’s see how you could do that:

CompanyService.java

package com.jwt.rest;

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

@Path("/company")
public class CompanyService {

	@GET
	public Response getEmployee() {

		String output = " This is the list of employees:";

		// code to retrieve the list of employee

		return Response.status(200).entity(output).build();

	}

	@GET
	@Path("/permanent")
	public Response getPermanentEmployee() {

		String output = " This is the list of permanenet employee:";

		// code to retrieve the list of permanenet employee

		return Response.status(200).entity(output).build();

	}

	@GET
	@Path("/contract")
	public Response getContractEmployee() {

		String output = " This is the list of contract employee:";

		// code to retrieve the list of contract employee

		return Response.status(200).entity(output).build();

	}

}

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


1st URL

http://localhost:8080/RESTPathExample/rest/company

Output :

This is the list of employees:

2nd URL

http://localhost:8080/RESTPathExample/rest/company/permanent

Output :

This is the list of permanent employee:

3rd URL

http://localhost:8080/RESTPathExample/rest/company/contract

Output :

This is the list of contract Employee:


Dynamic URI with parameter matching:

In your @Path annotation URI value, anything between "{" and "}" braces can be dynamic. This value can be mapped to method input variable using @PathParam annotation.For example let’s say we want to list all information about a employee, client needs to provide just a employee id.

EmployeeService.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("/employee")
public class EmployeeService {

	@GET
	@Path("/{empID}")
	public Response getMemberInfo(@PathParam("empID") String empID) {

		String output = " This is information of employee whose ID is : "
				+ empID;

		// code to retrieve employee info

		return Response.status(200).entity(output).build();
	}
}

Access your page by typing following URL


URL

http://localhost:8080/RESTPathExample/rest/employee/101

Output :

This is information of employee whose ID is : 101


URI Matching and Regular Expression :

@Path expressions are not limited to simple wildcard matching expressions. For example, our getMemberInfo() method takes an integer parameter. We can change our @Path value to only match digits:

@Path("/employee")
public class EmployeeService {

   @GET
   @Path("{id : \\d+}")
   public Response getMemberInfo(@PathParam("id") int id) {
      ...
   }
}

Example:

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: [0-9]+}")
	public Response getEmployeeById(@PathParam("empId") String empId) {

		return Response
				.status(200)
				.entity(" getEmployeeById() method called ...Got employee with id : "
						+ empId).build();
	}

	@GET
	@Path("/name/{empName: [a-zA-Z\\s]+}")
	public Response getEmployeeByName(@PathParam("empName") String name) {

		return Response
				.status(200)
				.entity("getEmployeeByName() method called ...Got employee with name : "
						+ name).build();
	}
}

Output:

In the above example, if you use "http://localhost:8080/RESTPathExample/rest/employee/101" URI , getEmployeeById() method will be invoked, and you will get "getEmployeeById() method called ...Got employee with id : 101" as a response.

If you use "http://localhost:8080/RESTPathExample/rest/employee/name/mukesh" URI , then getEmployeeByName() method will be invoked and you will get "getEmployeeByName() method called ...Got employee with name : mukesh " as a response.





References :- JAX-RS Documentation



Related Articles

  1. Maven Overview


comments powered by Disqus