How to: A REST-Service in Java using Jersey | Dockerize a Java-Application – Part 1

Hay Steemers,

this is a new tutorial in which we will create a simple REST-Service using Java. The clue about this is, that we will also dockerize this application, meaning that we will make it possible to run this application as a docker container.

DOCKERANDJERSEY
Source

This tutorial series will be based on the example application that we‘ve created in part 2 and we will use the build environment of part 4.3, so if you haven‘t read those parts jet, you should step through that tutorial series first.

We will start with a small motivation about why the heck do we want to run our application as a docker container. After that we will directly start to add some new code to our example application.

Motivation

There are a bunch of good reasons for putting an application into a container. The most important ones for us are:

  • Scalability
  • Build once, run everywhere
  • You don’t have to care about bounding systems

Scalability

As you have seen in the improve your software development series, it is damn easy to run a docker container. So if your application needs to handle more users, you can just start another instance and put a load balancer in front of it – That‘s pretty easy!

There is one prerequisite to do so: The application needs to be stateless. And wolla, this is the reason why our application will be a REST-Service which is stateless by design ;)

Build once, run everywhere

Docker can be installed and used on nearly every OS and hardware. You can even use your raspberry PI.

You don’t have to care about bounding systems

When creating a Docker image, we can make sure that it contains all the bounding systems that are needed by our application.

Creating a REST-Service in Java-App

Okay, you now know the benefits of a dockerized application and you also know reason, why we are going to implement a REST-Service. Another reason is, that a REST-Service as a backend can be used by several different frontend systems. It is possible to use the same backend for a single site application and a mobile app at the same time.

At this point I thought about explaining what a REST-Service is about, but there are a bunch of good articles out there in the web, like this one, so I’ll skip this part. But if you do not know what a REST-Service is, you should definitely have a look at some articles before continuing.

Now that you know what a REST-Service is, I will know show you how to create one in Java using the Jersey-Framework. Jersey itself is the most common implementation of the JAX-RS API which allows you to create REST-Services under the use of annotations.

The JAX-RS API for developing RESTful web services is a Java programming language API designed to make it easy to develop applications that use the REST architecture.
The JAX-RS API uses Java programming language annotations to simplify the development of RESTful web services. Developers decorate Java programming language class files with HTTP-specific annotations to define resources and the actions that can be performed on those resources. Jersey annotations are runtime annotations, therefore, runtime reflection will generate the helper classes and artifacts for the resource, and then the collection of classes and artifacts will be built into a web application archive (WAR). The resources are exposed to clients by deploying the WAR to a Java EE or web server.
Source

Adding Jersey-Dependencies to the pom.xml

To use the Jersey Framework we have to add to our project first. As we are using Maven, this is pretty easy. Just add the following dependencies to the pom.xml

[.]
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.version}</version>
        </dependency>
    </dependencies>
[.]
    <properties>
        <jersey.version>2.24</jersey.version>
        <sonar.host.url>http://sonarqube:9000
    </properties>
[...]

We also have to change the type of artifact that will be created as we want to build a web service. So change the packaging from jar to war:

<packaging>war</packaging>

Good job!

Convert our Project into a Web-Project

Our example application was a normal Java-Application so far, but we now need a Web-Project – So what do we have to do? The first thing is already done by changing the package type to “war” in the pom.xml. Due to this change, maven will automatically create a WAR which can be deployed into a web-server like Tomcat.

But there is additional change required: We need a web.xml.

Web.xml

I don’t want to describe the function of this file in detail. Let’s just say this file is used to tell the web-server which files he has to start.

Create the following folder “/src/main/webapp/WEB-INF/ “ and add a file called “web.xml” to it.

WEBAPP
Full Size

We basically tell Jersey, that it should look into the package “com.example.steemit.endpoints” to find our REST-Services. We also tell the web-server, that it should start the servlet “dez1337Example” on startup. And the last thing we define is the base URL of this servlet.

Due to that configuration, our REST-Services of the package “com.example.steemit.endpoints” will be loaded on server startup and will be accessible under the URL “http://$WEBSERVER/rest/”.

Our first REST-Service

We will now create our first REST-Service. It will be a simple “HelloWorld” service, that retrieves a name as an input and returns “Hello $NAME”.

This service should be available under the following URL “http://$WEBSERVER/rest/sayHelloTo/$NAME”.

To do so, create a new package called “example.steemit.com.endpoints” and add a new class to this package. Mine is named “HelloWorldEndpoint”:

HelloWorldClass
Full size

The first thing we do is to tell jersey the URL for this service. To do so, we add the “@Path” annotation to our class.

package example.steemit.com.endpoints;

import javax.ws.rs.Path;

@Path("/sayHelloTo")
public class HelloWorldEndpoint {

}

Great! Before we create the method, we should think about what this method has to provide. According to our target URL, we have one URL-Parameter which is the $NAME. Also, the method should be accessible by a simple HTTP-GET request. And the last point: It should return a simple String.

Under the use of Jersey, the method will look like this:

    @GET
    @Path("/{name}")
    public String sayHelloWorld(@PathParam("name") String name) {
        return "Hello " + name;
    }

Did you thought that this would be that easy? We’ve created our first REST-Service in seconds with a really easy Framework – Pretty cool!

Test our changes

Can we test our changes and run the REST-Service? I am sorry, but we are not able to run the things right now, because we haven’t created a Web-Server so far.

Summary

Today we learned some basic reasons for using a combination of Docker and REST-Services and already started to build our own one. In the next part we will add a Web-Server directly into our application using the “embedded tomcat” project – So stay tuned for that and make sure you follow me. If you aren’t, just press the button below.

alt text
Source

Thank you and best regards!

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now