Hello World with Jersey framework

In this tutorial, I will show a simple example, guide to you all how to use the Jersey framework, an implementation of JAX-RS (Java API for RESTful Web Services) Specification, to create a RESTful Web Services in Java.

First of all, I will create a new Maven project with the packaging is a war file (Web Application), for example:

Hello World with Jersey framework

Once created, you will notice an error from Eclipse that we are missing a web.xml file which will be used to configure and register the servlet. To fix this error, please create a new web.xml file located in the /src/main/webapp/WEB-INF folder.

Hello World with Jersey framework

To work with the Jersey framework, we need to add its dependencies:

And to run the application, I will use Maven Jetty Plugin:

In this example, we will create a RESTful Web Services application that contains a GET request and when the user requests to this GET request, it will return a simple text “Hello World!”.

OK, let’s get start!

There are 2 steps we need to do:

  • Create a new class to create RESTful Web Services using the Jersey framework.

In this example, we will create a new class called HelloJersey in the package com.huongdanjava.jersey:

Hello World with Jersey framework

with the @Path annotation comes with it as follows:

Here, the @Path annotation is used to declare a request URL, which is required even though we do not explicitly define the request URL (“/”).

To create a new GET request “/ hello” in our application, we will add a new method in the HelloJersey class with the @GET annotation and the @Path annotation with the value “/ hello” as follows:

With this declaration, Jersey will create a new GET request with the URL to access as “/ hello”.

  • The second step we need to do is to define the Servlet configuration in the web.xml file.

To do this, just open the web.xml file and add the following content:

In this servlet configuration file, I declared a servlet using Jersey’s org.glassfish.jersey.servlet.ServletContainer class called appServlet and configured this servlet to handle all requests from the user starting with “/” .

In this declaration. I also specified the package name containing the classes defining the request URL using the Jersey framework in our application.

Now, let’s try to run this example.

You will see the following results:

Hello World with Jersey framework


Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment