Implementing a RESTful service using Jersey

So far, we have discussed what web services are, how to implement them in a REST style, and the different HTTP methods and status codes. Now that we're familiar with these, let's take a look at the RESTful services in action.

We use Jersey to implement a RESTful web service. Jersey RESTful Web Services is an open source framework for developing RESTful web services. It is a reference implementation of JAX-RS and it provides support for JAX-RS APIs. It adds some of its own features and APIs that extend from the JAX-RS toolkit for the simplification of web service development. 

We will create a Maven web project, add the Jersey dependency, and define resources and functions in order to respond to the HTTP request.

Create a Maven web project and add the dependencies as follows:

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>>${jersey.version}</version>
</dependency>

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>>${jersey.version}</version>
</dependency>

<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>

Let's write a really simple resource to start with. We will define a resource with a @GET annotation that returns a string as follows:

@Path("/home")
public class Controller {
@GET
fun home(): String {
return "hello"
}
}

Here we have defined a resource, /home, and a function, home(), that just return a string. Build this application and deploy it on a server.

We have deployed the service developed on Tomcat on port 8080. When we access localhost:8080/home, the browser sends a GET request and the endpoint, /home, is mapped to the home() function, which returns the string message. The following screenshot depicts this:

Similarly, let's add another resource called /greet like this:

@Path("/greet")
public class HelloWorld {

@GET
@Path("{parameter}")
fun greet(@PathParam("parameter") name: String): Response {
val response = "Hello : $name"
return Response.status(200)
.entity(response)
.build()
}
}

This resource is accessible via localhost:8080/greet/{{name}}. Once we invoke this resource, we get a greet message back. Consider the following screenshot:

We have now created a simple application to illustrate RESTful web services.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset