RESTful service with Spring and Jersey

1. Introduction to Jersey

Jersey, is something I have started hearing of more frequently around me.

Jersey, basically is a RESTful Web Services framework to develop RESTful Web Services in Java. It is a reference implementation of JAX-RS specification to develop RESTful web service.

1.1 What is a reference implementation?

Found a great answer to this on Stack Overflow –


In theory, at least, there could be many different implementations of that specification; multiple vendors could all implement their own versions of the spec, all of which followed the specification, but some were faster, or more robust, or used less memory, etc. The reference implementation is simply the implementation of a specification that is offered as an example of how the specification might be implemented. Having a RI makes it easier for other implementors to understand the intent of a specification. Sometimes the RI is just a toy, and no one uses it; other times, the RI is also the best implementation.

– Credits to Ernest Friedman-Hill

2. Jersey vs Spring REST

Basically the implementations are quite similar, each having their respective annotation specification, like a @RequestMapping in Spring is equivalent to @Path in Jersey, @PathVariable in Spring is equivalent to @PathParam in Jersey, and so on.

Choosing between the two would be really difficult. So if our application is already on Spring, Spring REST should be the preferred choice.

In this tutorial, we will be creating a very simple RESTful application with Spring and Jersey so you can easily understand the integration, application flow and get started.

Jersey provides support for using Spring in the REST layer (by specifying jersey-servlet into web.xml instead of the spring dispatcher servlet). That enables Spring to scan for components in the Jersey package.

3. Implementation with Spring and Jersey

Let’s quick start with the implementation, which is quite straightforward.

Firstly, let’s make sure the following pom file entries are present.

pom.xml

Let’s update the web.xml file, which has the needed integration of Jersey with Spring. Specify the Jersey servlet as can be seen highlighted in the below code snippet.

web.xml

It will be the Employee entity we will be dealing with. So let’s create it.

Employee.java

Now let’s write the REST service with Jersey.

EmployeeService.java

For scanning the Spring component, we need to add component-scan into applicationContext file.

applicationContext.xml

4. Running the application

Spring and Jersey

5. Useful links

6. Download source code

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.