Basic about Jakarta EE RESTful Web Services

Jakarta EE RESTful Web Services define the required specification of a RESTful Web Service in Java. Make it possible for us to implement RESTful Web Services applications with Java. In this tutorial, I will introduce the basics of Jakarta EE RESTful Web Services that you need to know!

First, I will create a new Jakarta EE Maven project as an example:

There are two implementations for Jakarta EE RESTful Web Services, Eclipse Jersey and JBoss RESTEasy. I will use Jersey as the main implementation for the Huong Dan Java tutorials about Jakarta EE RESTful Web Services.

I will declare Jersey dependencies as follows:

You can remove the dependency jakarta.jakartaee-api in the Maven project that you have created according to my instruction, because for each module of Jakarta EE, there will be a corresponding dependency. For example, for Jakarta EE RESTful Web Services, the dependency name is jakarta.jaxrs-api. And this dependency, when we declare Jersey, is automatically included:

Now, I 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!”!

To do this, first, I will create a new class that exposes the request “/hello” and returns the text “Hello World” when the user requests it. The content of this class is as follows:

If you have worked on the Spring framework to expose RESTful APIs, you can imagine that the @Path annotation in the above example corresponds to Spring’s @RequestMapping annotation.

The @Path annotation is used to declare a request URL. This annotation has only one attribute, value() for us to define the request URL. If you declare it at the class level like the above example, the value of the attribute value() in this annotation will be the prefix for all the requests that we define at the method level. Therefore, the request URL in our example will be “/hello” as we want.

Annotation @GET to define the HTTP GET method for the “/hello” request. Jakarta EE RESTful Web Services supports all HTTP methods, depending on the purpose you can use.

Next step, we need to declare Jersey Servlet Container with Server Runtime so that Jersey Servlet can be used by Server Runtime to handle all requests from users.

I will use the web.xml file to do this as follows:

When declaring Jersey’s HttpServlet ServletContainer, we need to specify the packages that we are exposing the RESTful APIs to in our application.

Now, if you run the application with the Maven Jetty Plugin defined in the project and request to the URL http://localhost:8080/hello, you will see the following result:

1/5 - (1 vote)

Add Comment