REST Hello World with Jersey

The below example describes publishing a simple JAX-RS REST Hello World with Jersey 2.5 on Apache Tomcat.

1. Project Setup

Lets create a Jersey Maven Web Application Project with the below pom.xml

2. Code Application class

Code an Application class which is basically a configuration class for our REST Application

Our application class extends ResourceConfig, within the constructor of our application class we specify the packages to be scanned by Jersey for Resource Clasess (RESTful Webservices).

In the above example we as Jersey to scan the package com.heapcode.resource for any Resource classes.

3. Configure web.xml

The web.xml for the project looks something like this

In the web.xml  we declare the application class we just coded. In the next step we specify against which all URL patterns this servlet should be called or invoked. Here in this case “/*” which tells the servlet to be invoked for all URL patterns.

4. Code Resource Class or Webservice class

1. In the above Resource class we specify that all the APIs within this class always produce TEXT_PLAIN response, the other types are XML, JSON, ATOM etc. We shall consider other formats later.

2. We specify the path as “/hello” this is the path for the Resource Class, we can in turn have subpath against this path in the methods of this class say something like “/hello/subpath1/” and “/hello/subpath2/”.

3. Next we shall create a method within the above class as sayHello() , this method just returns a plain String Hello World. We annotate his method GET which specifies that this would be called when we invoke HTTP GET against the path “/hello”

4. Lets create another method within the above class as sayHello(String name) , this method just returns a plain String Hello World along with the name. We annotate his method GET which specifies that this would be called when we invoke HTTP GET against the path “/hello/name”. This method is an example for method class with PathParam,  in this case Path is different it accepts a parameter.

7. Output:

Jersey Hello World Output 1

Jersey Hello World Output 2

8. Project Structure:

Jersey Hello World Project Structure


I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.

Leave a Reply

Your email address will not be published. Required fields are marked *