Jersey Path Annotation

 

In Jersey, @Path annotation is used to create RESTful web services.

Java objects annotated with @Path have at least one method annotated with @Path or a request method designator annotation such as @GET, @POST,..

In this example, we will see how to use @Path annotation on class level and on resource methods.

 

1. Technologies used

  • Jersey 2.13
  • Maven 3.0.5
  • Eclipse 4.2
  • JDK 1.6
  • Tomcat 6.0

 

2. Project structure

We create a web application project using Maven.

Jersey-Path-Annotation

 

3. Jersey dependency

 

4. REST Service

File : HelloService

Annotating HelloService class with @Path("/hello") means that HelloService will be hosted at the URI path : /hello

The /hello value on @Path is relative to the base URI of server on which the web service is deployed.

On sayHello() method, we doesn’t use @Path, it means that this method will process all HTTP GET requests maked with the URI path /hello

On sayHelloWorld() method, we have added an URI path to which the method will respond, so it will be invoked by calling an HTTP GET of /hello/world

On sayHelloParam() method, we have used an URI template by adding the name variable to the URI. In order to obtain the value of this variable, we have used @PathParam on the name argument.

On sayHelloRegex() method, we have declared a regular expression on the URI template variable name. In this case, the value of the name variable must match with the expression [a-zA-Z][a-zA-Z_0-9]+ , unless a [404 -Not Found] response will occur.

 

5. Web app configuration

 

6. Test It

URL : http://localhost:8080/Jersey-Path-Annotation/hello/

Jersey-Path-Annotation-1

 

URL : http://localhost:8080/Jersey-Path-Annotation/hello/world

Jersey-Path-Annotation-2

 

URL : http://localhost:8080/Jersey-Path-Annotation/hello/param/Walid

Jersey-Path-Annotation-3

 

URL : http://localhost:8080/Jersey-Path-Annotation/hello/regex/Khadija26

Jersey-Path-Annotation-4

 

URL : http://localhost:8080/Jersey-Path-Annotation/hello/regex/26Khadija

Jersey-Path-Annotation-5

 

 

Download source code

Reference