Jersey Hello World Example

Jersey RESTful Web Services 3.x framework is an open source, production quality, framework for developing REST APIs that supports Jakarta RESTful Web Services 3.0 specification. Implementation-wise, Jersey provides a few own APIs that extend the JAX-RS spec with additional features and utilities to simplify RESTful service and client development further. 

This tutorial will help you set up the Jersey environment in your local machine and get started with a simple Hello World REST API.

1. Create a Maven Application

Start with creating a blank Maven application and add the following dependencies.

  • jakarta.ws.rs:jakarta.ws.rs-api – imports the Jakarta RS specification of REST APIs.
  • org.glassfish.jersey.containers:jersey-container-jetty-http – imports the Jersey core libraries and jars to deploy the application in the Jetty server.
  • org.glassfish.jersey.inject: jersey-hk2 – HK2 is a light-weight and dynamic dependency injection framework. This dependency provides integration between Jersey and HK2.
<properties>
	<jakarta.ws.version>3.1.0</jakarta.ws.version>
	<jersey.version>3.1.6</jersey.version>
	<maven.compiler.source>21</maven.compiler.source>
	<maven.compiler.target>21</maven.compiler.target>
</properties>

<dependencies>

	<dependency>
	  <groupId>jakarta.ws.rs</groupId>
	  <artifactId>jakarta.ws.rs-api</artifactId>
	  <version>${jakarta.ws.version}</version>
	</dependency>

	<dependency>
	  <groupId>org.glassfish.jersey.containers</groupId>
	  <artifactId>jersey-container-jetty-http</artifactId>
	  <version>${jersey.version}</version>
	</dependency>

	<dependency>
	  <groupId>org.glassfish.jersey.inject</groupId>
	  <artifactId>jersey-hk2</artifactId>
	  <version>${jersey.version}</version>
	</dependency>

</dependencies>

Apart from these dependencies, I have included the Lombok and JUnit 5 dependencies as well.

2. REST Resource

After the dependencies have been setup, we can write our first REST API using the Jakarta-RS annotations. The following API is an example REST API that returns a list of two items in the JSON response.

import com.howtodoinjava.demo.resources.model.Item;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.util.List;

@Path("items")
public class MyResource {

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public List getAll() {
    return List.of(new Item(1L, "Item1"), new Item(2L, "Item2"));
  }
}

And the Item class is:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Item {

  long id;
  String name;
}

3. Application Class

In Jersey, the resources and providers are configured via an application-supplied subclass of jakarta.ws.rs.core.Application. An implementation MAY provide alternate mechanisms for locating resource classes and providers (e.g. runtime class scanning) but the use of Application class is the only portable means of configuration.

In Jersey, org.glassfish.jersey.server.ResourceConfig class extends the Application class and provides the resource configuration for configuring a web application.

In our application, we extend the ResourceConfig class and it acts as the entry point for our application.

import org.eclipse.jetty.server.Server;
import org.glassfish.jersey.jetty.JettyHttpContainerFactory;
import org.glassfish.jersey.server.ResourceConfig;

import jakarta.ws.rs.ApplicationPath;

import java.net.URI;

@ApplicationPath("/")
public class Main extends ResourceConfig {

  public static final String BASE_URI = "http://localhost:8080/";

  public Main() {
    packages("com.howtodoinjava.demo.resources");
  }

  public static void main(String[] args) {
    startServer();
  }

  public static Server startServer() {
    Server server = JettyHttpContainerFactory.createServer(URI.create("http://localhost:8080/"), new Main());
    System.out.println("Jersey application started at http://localhost:8080/");
    System.out.println("Press Ctrl+C to stop the server.");
    return server;
  }
}

To test the application in IDE, we have created a main() method and started the Jetty server. In other environments, this code will not be executed and application servers will automatically detect the Application class and configure it.

4. Test the Application

To test the application, run the main() method that will start the embedded Jetty server and deploy the REST API in it.

Jersey application started at http://localhost:8080/
Press Ctrl+C to stop the server.

Now, we can type the below URL in the browser: http://localhost:8080/items

It will call the REST API method and print the items in the browser window.

The API has been successfully deployed.

5. Unit Testing

We have already included the JUnit 5 dependencies in the application, so we can directly write the unit tests. The unit test starts the embedded server using the method Main.startServer() written in the main application that deploys all REST APIs as well.

Next, we use jakarta.ws.rs.client.WebTarget class to invoke the REST APIs and verify their outputs.

import com.howtodoinjava.demo.Main;
import com.howtodoinjava.demo.resources.model.Item;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import org.eclipse.jetty.server.Server;
import org.junit.jupiter.api.*;

import java.util.List;

public class MyResourceTest {

  private Server server;
  private WebTarget target;

  @BeforeEach
  public void setUp() throws Exception {
    server = Main.startServer();

    Client c = ClientBuilder.newClient();
    target = c.target(Main.BASE_URI);
  }

  @AfterEach
  public void tearDown() throws Exception {
    server.stop();
  }

  @Test
  public void testGetAllItems() {
    List<Item> items = target.path("items").request().get(List.class);
    Assertions.assertEquals(2, items.size());
  }
}

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode