Spring Boot Jersey tutorial shows how to set up a simple RESTFul application with Jersey in a Spring Boot application. Jersey is an alternative to Spring RESTFul applications created with @RestController.

Spring is a popular Java application framework for creating enterprise applications. Spring Boot is the next step in evolution of Spring framework. It helps create stand-alone, production-grade Spring based applications with minimal effort. It promotes using the convention over configuration principle over XML configurations.

RESTFul application

A RESTFul application follows the REST architectural style, which is used for designing networked applications. RESTful applications generate HTTP requests performing CRUD (Create/Read/Update/Delete) operations on resources. RESTFul applications typically return data in JSON or XML format.

JAX-RS

Java API for RESTful Web Services (JAX-RS) is a Java programming language API specification that provides support in creating web services according to the Representational State Transfer (REST) architectural pattern. JAX-RS uses annotations to simplify the development and deployment of web service clients and endpoints. JAX-RS is an official part of Java EE.

JAX-RS  = Java API for RESTful Web Services

The X remained as part of the nomenclature. e.g.:

JAXR    = Java API for XML Registries
JAXP    = Java API for XML Processing
JAXB    = Java Architecture for XML Binding
JAX-RPC = Java API for XML-based RPC
JAX-WS  = Java API for XML Web Services  

So, the letter X is for XML.

It was just carried over from JAX-WS and the other javax.ws.rs so it can be said that the x comes from java(x) of the java package.

JAX-RS vs JAX-WS

JAX-WS – is Java API for the XML-Based Web Services – x`a standard way to develop a Web- Services in SOAP notation (Simple Object Access Protocol).

Calling of the Web Services is performed via remote procedure calls. For the exchange of information between the client and the Web Service is used SOAP protocol. Message exchange between the client and the server performed through XML– based SOAP messages.

Clients of the JAX-WS Web- Service need a WSDL file to generate executable code that the clients can use to call Web- Service.

JAX-RS – Java API for RESTful Web Services. RESTful Web Services are represented as resources and can be identified by Uniform Resource Identifiers (URI). Remote procedure call in this case is represented a HTTP– request and the necessary data is passed as parameters of the query. Web Services RESTful – more flexible, can use several different MIME– types. Typically used for XML data exchange or JSON (JavaScript Object Notation) data exchange…

REST vs RESTful

Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an “architectural style” that basically exploits the existing technology and protocols of the Web. REST (REpresentation State Transfer) is an architecture using which WebServices are created.

RESTful is typically used to refer to web services implementing such an architecture and RESTful is way of writing services using the REST architectures. A service based on REST is called a “RESTful service”. RESTful services exposes the resources to identify the targets to interact with clients.

Think of REST as an architectural “class” while RESTful is the well known “instance” of that class.

REST (REpresentational State Transfer) is basically an architectural style of development having some principles:

  • It should be stateless
  • It should access all the resources from the server using only URI
  • It does not have inbuilt encryption
  • It does not have session
  • It uses one and only one protocol – HTTP
  • For performing CRUD operations, it should use HTTP verbs such as get, post, put and delete
  • It should return the result only in the form of JSON or XML, atom, OData etc. (lightweight data )

REST based services follow some of the above principles and not all

RESTFUL services means it follows all the above principles.

It is similar to the concept of:

Object oriented languages support all the OOP concepts, examples: C++, C#

Object-based languages support some of the OOP features, examples: JavaScript, VB


Example:

ASP Dot NET MVC 4 is REST-Based while Microsoft WEB API is RESTFul.

MVC supports only some of the above REST principles whereas WEB API supports all the above REST Principles.

MVC only supports the following from the REST API

  • We can access the resource using URI
  • It supports the HTTP verb to access the resource from server
  • It can return the results in the form of JSON, XML, that is the HTTPResponse.

However, at the same time in MVC

  • We can use the session
  • We can make it stateful
  • We can return video or image from the controller action method which basically violates the REST principles

That is why MVC is REST-Based whereas WEB API supports all the above principles and is RESTFul.

Here you have some links to check

RESTful programming

REST is the underlying architectural principle of the web. The amazing thing about the web is the fact that clients (browsers) and servers can interact in complex ways without the client knowing anything beforehand about the server and the resources it hosts. The key constraint is that the server and client must both agree on the media used, which in the case of the web is HTML.

An API that adheres to the principles of REST does not require the client to know anything about the structure of the API. Rather, the server needs to provide whatever information the client needs to interact with the service. An HTML form is an example of this: The server specifies the location of the resource and the required fields. The browser doesn’t know in advance where to submit the information, and it doesn’t know in advance what information to submit. Both forms of information are entirely supplied by the server. (This principle is called HATEOAS: Hypermedia As The Engine Of Application State.)

So, how does this apply to HTTP, and how can it be implemented in practice? HTTP is oriented around verbs and resources. The two verbs in mainstream usage are GET and POST, which I think everyone will recognize. However, the HTTP standard defines several others such as PUT and DELETE. These verbs are then applied to resources, according to the instructions provided by the server.

For example, Let’s imagine that we have a user database that is managed by a web service. Our service uses a custom hypermedia based on JSON, for which we assign the mimetype application/json+userdb (There might also be an application/xml+userdb and application/whatever+userdb – many media types may be supported). The client and the server have both been programmed to understand this format, but they don’t know anything about each other. As Roy Fielding points out:

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.

A request for the base resource / might return something like this:

Request

GET /
Accept: application/json+userdb

Response

200 OK
Content-Type: application/json+userdb

{
    "version": "1.0",
    "links": [
        {
            "href": "/user",
            "rel": "list",
            "method": "GET"
        },
        {
            "href": "/user",
            "rel": "create",
            "method": "POST"
        }
    ]
}

We know from the description of our media that we can find information about related resources from sections called “links”. This is called Hypermedia controls. In this case, we can tell from such a section that we can find a user list by making another request for /user:

Request

GET /user
Accept: application/json+userdb

Response

200 OK
Content-Type: application/json+userdb

{
    "users": [
        {
            "id": 1,
            "name": "Emil",
            "country: "Sweden",
            "links": [
                {
                    "href": "/user/1",
                    "rel": "self",
                    "method": "GET"
                },
                {
                    "href": "/user/1",
                    "rel": "edit",
                    "method": "PUT"
                },
                {
                    "href": "/user/1",
                    "rel": "delete",
                    "method": "DELETE"
                }
            ]
        },
        {
            "id": 2,
            "name": "Adam",
            "country: "Scotland",
            "links": [
                {
                    "href": "/user/2",
                    "rel": "self",
                    "method": "GET"
                },
                {
                    "href": "/user/2",
                    "rel": "edit",
                    "method": "PUT"
                },
                {
                    "href": "/user/2",
                    "rel": "delete",
                    "method": "DELETE"
                }
            ]
        }
    ],
    "links": [
        {
            "href": "/user",
            "rel": "create",
            "method": "POST"
        }
    ]
}

We can tell a lot from this response. For instance, we now know we can create a new user by POSTing to /user:

Request

POST /user
Accept: application/json+userdb
Content-Type: application/json+userdb

{
    "name": "Karl",
    "country": "Austria"
}

Response

201 Created
Content-Type: application/json+userdb

{
    "user": {
        "id": 3,
        "name": "Karl",
        "country": "Austria",
        "links": [
            {
                "href": "/user/3",
                "rel": "self",
                "method": "GET"
            },
            {
                "href": "/user/3",
                "rel": "edit",
                "method": "PUT"
            },
            {
                "href": "/user/3",
                "rel": "delete",
                "method": "DELETE"
            }
        ]
    },
    "links": {
       "href": "/user",
       "rel": "list",
       "method": "GET"
    }
}

We also know that we can change existing data:

Request

PUT /user/1
Accept: application/json+userdb
Content-Type: application/json+userdb

{
    "name": "Emil",
    "country": "Bhutan"
}

Response

200 OK
Content-Type: application/json+userdb

{
    "user": {
        "id": 1,
        "name": "Emil",
        "country": "Bhutan",
        "links": [
            {
                "href": "/user/1",
                "rel": "self",
                "method": "GET"
            },
            {
                "href": "/user/1",
                "rel": "edit",
                "method": "PUT"
            },
            {
                "href": "/user/1",
                "rel": "delete",
                "method": "DELETE"
            }
        ]
    },
    "links": {
       "href": "/user",
       "rel": "list",
       "method": "GET"
    }
}

Notice that we are using different HTTP verbs (GET, PUT, POST, DELETE etc.) to manipulate these resources, and that the only knowledge we presume on the client’s part is our media definition.

Further reading:

(This answer has been the subject of a fair amount of criticism for missing the point. For the most part, that has been a fair critique. What I originally described was more in line with how REST was usually implemented a few years ago when I first wrote this, rather than its true meaning. I’ve revised the answer to better represent the real meaning.)

RESTful API

This answer is for absolute beginners, let’s know about most used API architecture today.

To understand Restful programming or Restful API. First, you have to understand what API is, on a very high-level API stands for Application Programming Interface, it’s basically a piece of software that can be used by another piece of software in order to allow applications to talk to each other.

The most widely used type of API in the globe is web APIs while an app that sends data to a client whenever a request comes in.

In fact, APIs aren’t only used to send data and aren’t always related to web development or javascript or python or any programming language or framework.

The application in API can actually mean many different things as long as the pice of software is relatively stand-alone. Take for example, the File System or the HTTP Modules we can say that they are small pieces of software and we can use them, we can interact with them by using their API. For example when we use the read file function for a file system module of any programming language, we are actually using the file_system_reading API. Or when we do DOM manipulation in the browser, we’re are not really using the JavaScript language itself, but rather, the DOM API that browser exposes to us, so it gives us access to it. Or even another example let’s say we create a class in any programming language like Java and then add some public methods or properties to it, these methods will then be the API of each object created from that class because we are giving other pieces of software the possibility of interacting with our initial piece of software, the objects in this case. S0, API has actually a broader meaning than just building web APIs.

Now let’s take a look at the REST Architecture to build APIs.

REST which stands for Representational State Transfer is basically a way of building web APIs in a logical way, making them easy to consume for ourselves or for others.

To build Restful APIs following the REST Architecture, we just need to follow a couple of principles. 1. We need to separate our API into logical resources. 2. These resources should then be exposed by using resource-based URLs. 3. To perform different actions on data like reading, creating, or deleting data the API should use the right HTTP methods and not the URL. 4. Now the data that we actually send back to the client or that we received from the client should usually use the JSON data format, were some formatting standard applied to it. 5. Finally, another important principle of EST APIs is that they must be stateless.

Separate APIs into logical resources: The key abstraction of information in REST is a resource, and therefore all the data that we wanna share in the API should be divided into logical resources. What actually is a resource? Well, in the context of REST it is an object or a representation of something which has some data associated to it. For example, applications like tour-guide tours, or users, places, or revies are of the example of logical resources. So basically any information that can be named can be a resource. Just has to name, though, not a verb.

Expose Structure: Now we need to expose, which means to make available, the data using some structured URLs, that the client can send a request to. For example something like this entire address is called the URL. and this / addNewTour is called and API Endpoint.

Our API will have many different endpoints just like bellow

https://www.tourguide.com/addNewTour
https://www.tourguide.com/getTour
https://www.tourguide.com/updateTour
https://www.tourguide.com/deleteTour
https://www.tourguide.com/getRoursByUser
https://www.tourguide.com/deleteToursByUser

Each of these API will send different data back to the client on also perform different actions. Now there is something very wrong with these endpoints here because they really don’t follow the third rule which says that we should only use the HTTP methods in order to perform actions on data. So endpoints should only contain our resources and not the actions that we are performed on them because they will quickly become a nightmare to maintain.

How should we use these HTTP methods in practice? Well let’s see how these endpoints should actually look like starting with /getTour. So this getTour endpoint is to get data about a tour and so we should simply name the endpoint /tours and send the data whenever a get request is made to this endpoint. So in other words, when a client uses a GET HTTP method to access the endpoint,

(we only have resources in the endpoint or in the URL and no verbs because the verb is now in the HTTP method, right? The common practice to always use the resource name in the plural which is why I wrote /tours nor /tour.) The convention is that when calling endpoint /tours will get back all the tours that are in a database, but if we only want the tour with one ID, let’s say seven, we add that seven after another slash(/tours/7) or in a search query (/tours?id=7), And of course, it could also be the name of a tour instead of the ID.

HTTP Methods: What’s really important here is how the endpoint name is the exact same name for all.

GET: (for requesting data from the server.)
https://www.tourguide.com/tours/7

POST: (for sending data to the server.)
https://www.tourguide.com/tours

PUT/PATCH: (for updating requests for data to the server.) 
https://www.tourguide.com/tours/7

DELETE: (for deleting request for data to the server.)
https://www.tourguide.com/tours/7

The difference between PUT and PATCH-> By using PUT, the client is supposed to send the entire updated object, while with PATCH it is supposed to send only the part of the object that has been changed.

By using HTTP methods users can perform basic four CRUD operations, CRUD stands for Create, Read, Update, and Delete.

Now there could be a situation like a bellow:

So, /getToursByUser can simply be translated to /users/tours, for user number 3 end point will be like /users/3/tours.

if we want to delete a particular tour of a particular user then the URL should be like /users/3/tours/7, here user id:3 and tour id: 7.

So there really are tons of possibilities of combining resources like this.

Send data as JSON: Now about data that the client actually receives, or that the server receives from the client, usually we use the JSON Data Format. A typical JSON might look like below:

Before sending JSON Data we usually do some simple response formatting, there are a couple of standards for this, but one of the very simple ones called Jsend. We simply create a new object, then add a status message to it in order to inform the client whether the request was a success, fail, or error. And then we put our original data into a new object called Data.

Wrapping the data into an additional object like we did here is called Enveloping, and it’s a common practice to mitigate some security issues and other problems.

Restful API should always be stateless: Finally a RESTful API should always be stateless meaning that, in a stateless RESTful API all state is handled on the client side no on the server. And state simply refers to a piece of data in the application that might change over time. For example, whether a certain user is logged in or on a page with a list with several pages what the current page is? Now the fact that the state should be handled on the client means that each request must contain all the information that is necessary to process a certain request on the server. So the server should never ever have to remember the previous request in order to process the current request.

Let’s say that currently we are on page five and we want to move forward to page six. Sow we could have a simple endpoint called /tours/nextPage and submit a request to server, but the server would then have to figure out what the current page is, and based on that server will send the next page to the client. In other words, the server would have to remember the previous request. This is what exactly we want to avoid in RESTful APIs.

Instead of this case, we should create a /tours/page endpoint and paste the number six to it in order to request page number six /tours/page/6 . So the server doesn’t have to remember anything in, all it has to do is to send back data for page number six as we requested.

Statelessness and Statefulness which is the opposite are very important concepts in computer science and applications in general

RESTfull Correction

There’s a lot of misconception out there about this concept. I always try to remember:

  1. Structured URLs and Http Methods/Verbs are not the definition of restful programming.
  2. JSON is not restful programming
  3. RESTful programming is not for APIs

I define restful programming as

An application is restful if it provides resources (being the combination of data + state transitions controls) in a media type the client understands

To be a restful programmer you must be trying to build applications that allow actors to do things. Not just exposing the database.

State transition controls only make sense if the client and server agree upon a media type representation of the resource. Otherwise there’s no way to know what’s a control and what isn’t and how to execute a control. IE if browsers didn’t know <form> tags in html then there’d be nothing for you to submit to transition state in your browser.

I’m not looking to self promote, but i expand on these ideas to great depth in my talk http://techblog.bodybuilding.com/2016/01/video-what-is-restful-200.html .

An excerpt from my talk is about the often referred to richardson maturity model, i don’t believe in the levels, you either are RESTful (level 3) or you are not, but what i like to call out about it is what each level does for you on your way to RESTful

REST Principles

The answer is very simple, there is a dissertation written by Roy Fielding. In that dissertation he defines the REST principles. If an application fulfills all of those principles, then that is a REST application.

The term RESTful was created because ppl exhausted the word REST by calling their non-REST application as REST. After that the term RESTful was exhausted as well. Nowadays we are talking about Web APIs and Hypermedia APIs, because the most of the so called REST applications did not fulfill the HATEOAS part of the uniform interface constraint.

The REST constraints are the following:

  1. client-server architecture
    So it does not work with for example PUB/SUB sockets, it is based on REQ/REP.
  2. stateless communication
    So the server does not maintain the states of the clients. This means that you cannot use server a side session storage and you have to authenticate every request. Your clients possibly send basic auth headers through an encrypted connection. (By large applications it is hard to maintain many sessions.)
  3. usage of cache if you can
    So you don’t have to serve the same requests again and again.
  4. uniform interface as common contract between client and server
    The contract between the client and the server is not maintained by the server. In other words the client must be decoupled from the implementation of the service. You can reach this state by using standard solutions, like the IRI (URI) standard to identify resources, the HTTP standard to exchange messages, standard MIME types to describe the body serialization format, metadata (possibly RDF vocabs, microformats, etc.) to describe the semantics of different parts of the message body. To decouple the IRI structure from the client, you have to send hyperlinks to the clients in hypermedia formats like (HTML, JSON-LD, HAL, etc.). So a client can use the metadata (possibly link relations, RDF vocabs) assigned to the hyperlinks to navigate the state machine of the application through the proper state transitions in order to achieve its current goal. For example when a client wants to send an order to a webshop, then it have to check the hyperlinks in the responses sent by the webshop. By checking the links it founds one described with the http://schema.org/OrderAction. The client know the schema.org vocab, so it understands that by activating this hyperlink it will send the order. So it activates the hyperlink and sends a POST https://example.com/api/v1/order message with the proper body. After that the service processes the message and responds with the result having the proper HTTP status header, for example 201 - created by success. To annotate messages with detailed metadata the standard solution to use an RDF format, for example JSON-LD with a REST vocab, for example Hydra and domain specific vocabs like schema.org or any other linked data vocab and maybe a custom application specific vocab if needed. Now this is not easy, that’s why most ppl use HAL and other simple formats which usually provide only a REST vocab, but no linked data support.
  5. build a layered system to increase scalability
    The REST system is composed of hierarchical layers. Each layer contains components which use the services of components which are in the next layer below. So you can add new layers and components effortless. For example there is a client layer which contains the clients and below that there is a service layer which contains a single service. Now you can add a client side cache between them. After that you can add another service instance and a load balancer, and so on… The client code and the service code won’t change.
  6. code on demand to extend client functionality
    This constraint is optional. For example you can send a parser for a specific media type to the client, and so on… In order to do this you might need a standard plugin loader system in the client, or your client will be coupled to the plugin loader solution.

REST constraints result a highly scalable system in where the clients are decoupled from the implementations of the services. So the clients can be reusable, general just like the browsers on the web. The clients and the services share the same standards and vocabs, so they can understand each other despite the fact that the client does not know the implementation details of the service. This makes possible to create automated clients which can find and utilize REST services to achieve their goals. In long term these clients can communicate to each other and trust each other with tasks, just like humans do. If we add learning patterns to such clients, then the result will be one or more AI using the web of machines instead of a single server park. So at the end the dream of Berners Lee: the semantic web and the artificial intelligence will be reality. So in 2030 we end up terminated by the Skynet. Until then … 😉

Jersey

Jersey is an open source framework for developing RESTful Web Services in Java. It is a reference implementation of the Java API for RESTful Web Services (JAX-RS) specification.

Spring Boot Jersey example

The following application is a simpe Spring Boot RESTful application created with Jersey.

$ tree
.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── favtuts
    │   │           ├── Application.java
    │   │           ├── config
    │   │           │   └── JerseyConfig.java
    │   │           └── endpoint
    │   │               ├── HelloEndpoint.java
    │   │               └── ReverseReturnEndpoint.java
    │   └── resources
    └── test
        └── java
            └── com
                └── favtuts
                    └── ApplicationTests.java

Use Spring Tool Suite on Eclipse IDE to create Spring Project

Then select Jersey dependencies

This is the project structure pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.6</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.favtuts</groupId>
	<artifactId>SpringBootJersey</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootJersey</name>
	<description>Demo project for Spring Boot and Jersey</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jersey</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

This is the Maven build file. Spring Boot starters are a set of convenient dependency descriptors which greatly simplify Maven configuration. The spring-boot-starter-parent has some common configurations for a Spring Boot application. The spring-boot-starter-jersey is a starter for building RESTful web applications using JAX-RS and Jersey. It is an alternative to spring-boot-starter-web. The spring-boot-starter-test is a starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito.

The spring-boot-maven-plugin provides Spring Boot support in Maven, allowing us to package executable JAR or WAR archives. Its spring-boot:run goal runs the Spring Boot application. application.properties

server.port=8086
server.servlet.context-path=/api

spring.main.banner-mode=off

logging.level.org.springframework=DEBUG

In the application.properties file we write various configuration settings of a Spring Boot application. We set the port and the context path. With the banner-mode property we turn off the Spring banner.

We set the logging level for spring framework to ERROR. The application.properties file is located in the in the src/main/resources directory.

JerseyConfig.java

package com.favtuts.sbjersey;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;

import com.favtuts.sbjersey.service.HelloService;
import com.favtuts.sbjersey.service.ReverseService;

@Component
public class JerseyConfig extends ResourceConfig {
	
	public JerseyConfig() {
		register(HelloService.class);
		register(ReverseService.class);
	}
}

JerseyConfig registers two service classes.

HelloService.java

package com.favtuts.sbjersey.service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.springframework.stereotype.Service;

@Service
@Path("/hello")
public class HelloService {

	@GET
	@Produces("text/plain")
	public String hello() {
		return "Hello from Spring";
	}
}

This is the HelloService. The @Path annotation defines the URL to which the service class will respond. HelloService is annotated also with Spring’s @Service for autodetection. Our service method simply returns “Hello from Spring” message.

ReverseService.java

package com.favtuts.sbjersey.service;

import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.springframework.stereotype.Service;

@Service
@Path("/reverse")
public class ReverseService {
	
	@GET
	@Produces("text/plain")
	public String reverse(@QueryParam("data") @NotNull String data) {
		return new StringBuilder(data).reverse().toString();
	}
}

The reverse() service method returns a string which is reversed. It accepts one parameter, which cannot be null. @QueryParam binds the value(s) of a HTTP query parameter to a resource method parameter.

ApplicationTests.java

package com.favtuts.sbjersey;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class SpringBootJerseyApplicationTests {

	@Autowired
	private TestRestTemplate restTemplate;
	
	@Test
	public void hello() {
		ResponseEntity<String> entity = this.restTemplate.getForEntity("/hello", String.class);
		assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
		assertThat(entity.getBody()).isEqualTo("Hello from Spring");
	}
	
	@Test
	public void reverse() {
		ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse?data=regit", String.class);
		assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
		assertThat(entity.getBody()).isEqualTo("tiger");
	}
	
	@Test
	public void validataion() {
		ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse", String.class);
		assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
	}
}

In the ApplicationTests, we test the two endpoints.

Application.java

package com.favtuts.sbjersey;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class SpringBootJerseyApplication extends SpringBootServletInitializer {
	
	public static void main(String[] args) {
		new SpringBootJerseyApplication().configure(new SpringApplicationBuilder(SpringBootJerseyApplication.class)).run(args);
	}
}

The Application sets up the Spring Boot application. The @SpringBootApplication enables auto-configuration and component scanning.

Run the command bellow to trigger the test with ramdom port.

$ mvn compile test

....

[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  5.969 s
[INFO] Finished at: 2022-04-20T16:15:59+07:00
[INFO] ------------------------------------------------------------------------

With mvn spring-boot:run command, we run the application.

$ mvn spring-boot:run

The application is deployed on embedded Tomcat server.

$ curl localhost:8086/api/hello
Hello from Spring

With the curl command, we connect to the hello endpoint.

$ curl localhost:8086/api/reverse?data=summer
remmus

The summer’s characters are reversed.

In this tutorial, we have created a simple RESTFul application in Spring Boot with Jersey, which is the reference implementation of the JAX-RS specification.

Leave a Reply

Your email address will not be published. Required fields are marked *