Building RESTful Services with Java Using JAX-RS and Jersey — Sample Application

I’m working on a project that required a RESTful API implemented in Java. Jersey, the reference implementation for JAX-RS, made it easy to implement and deploy these services. I figured I’d share my sample application here.

Configuring Tomcat (or your own app server)

There are many options to initialize Jersey in your servlet container. Some of them require no XML configuration at all. For my application, I simply configured the Jersey Servlet in web.xml as follows:



NOTE: Using this type of initialization, the packages parameter defines which classes Jersey will scan for URL Paths to resolve: in this case, all the classes in org.coenraets.* packages.

Defining the REST API

Before working on the implementation, I identified that my simple application would require three services:

  1. Find all employees
  2. Find an employee by id
  3. Find a list of direct reports for a specific employee

Based on these requirements, I came up with the following REST API:

  1. /api/employees
    Returns all employees
  2. /api/employees/1
    Returns an employee identified by id (employee 1 in this case)
  3. /api/employees/1/reports
    Returns direct reports of an employee (employee 1 in this case)

Implementing the API

Once my API was defined, providing the implementation using JAX-RS was easy. I just created a Java class defined as follows:


import java.util.List;


public class EmployeeResource {

	EmployeeDAO dao = new EmployeeDAO();

	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
	public List<Employee> findAll() {
		return dao.findAll();

	@GET @Path("{id}")
	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
	public Employee findById(@PathParam("id") String id) {
		return dao.findById(Integer.parseInt(id));

	@GET @Path("{id}/reports")
	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
	public List<Employee> findByManager(@PathParam("id") String managerId) {
		return dao.findByManager(Integer.parseInt(managerId));

You annotate your class and methods with the path (@Path) and the content type (@Produces) they respond to. The serialization from model objects to the content type requested by the client happens automatically. In this application, the methods will return either JSON or XML depending on the content type requested by the client.

The approach you use to actually retrieve the data is, of course, totally up to you. In this example, I use a simple DAO, but you can of course use your own data access solution.

This application only required GET methods, but JAX-RS allows you to handle the other HTTP methods (@GET, @PUT, @POST, @DELETE and @HEAD).

Note that the package name matches the packages parameter defined in web.xml.

Testing the API

If you want to test your API before using it in a client application, you can invoke your REST services straight from a browser address bar. For example, try:

However, that doesn’t give you full control to test all the content types your API can return. A common option to test the different content types supported by your API is to use cURL and specify the content type requested in the Accept header:

curl -I -H’Accept:application/json’

Download the Source Code

Click here to download the source code (Eclipse Dynamic Web Project).

In my next post, I’ll share the client-side of the application: how to invoke these services using jQuery (and JSON).

  • That’s a good approach, but I prefer use Spring Web 3 Restfull support.
    On the last spring-flex-integration release, was released a Restfull integration for AMF outputs.
    You can use the same @Controller writing output on XML, Json or AMF formats… with it, we can build hibrids back-end for any front-end (html/jquery or extjs or event Flex Applications).

    Best Regards.

    • yeah it good working……………………………..!!!!!!!!!!!!!!!!

  • I’ve posted a post/screencast using Spring WEB Restfull support where I show hot to use the same @Controller with outputs in XML, JSON and AMF. (in portguese).

    Best Regards.

  • Pingback: Random Code » De un programador a otro programador » Crear un servidor REST con Jersey()

  • leo

    Brilliant tutorial, many thanks!

  • Kamal

    I am trying to run this example, I see employee.xml, and you are queering from a database called directory, should we create a database called directory and create a table called employee ? if so how to populate the table with the employees.xml data ?
    I did not understand, please your help is appreciated.

  • Kris


    I was wondering if you can help me with my mobile application. I am new to the development world and I am all over the place to understand the technology better. So I have already created a client-side mobile application and am trying to connect that to a Java backend and render data from SQL server.
    How can I make a call from the client side application to my back-end application that contains the business logic and DAO layer?


  • Alexk2009

    This tutorial and the downloaded application left me thinking I Understood what was going on.

    However when I access the app from the browser I only get XML back and have been unable to work out what parameter to add to get json back.

    There was one error in the project, the init-param was org.conraets and produced a container expection. When I changed that to it worked like a dream. Not one of my favourite dreams, but good enough. Thanks for this

  • ryan


    excellent tutorial.Thanks for posting this.I am looking to create a rest service to do crud on mysql database do u have any samples or tutorials on that?


  • Bob

    Thanks for putting all these great examples out there! I’ve ended up on your site while building a java + backbone.js web app countless times now. Extremely helpful.

  • asma

    thank you for posting this tutorial
    can i have the link of the next post, which client-side of the application ?


  • asma

    thank you for posting this tutorial
    can i have the link of the next post, which client-side of the application ?


  • Paul

    Thanks for the example.

  • Amol Powar

    Thanks for the example, this helped me understand the basis. Do you have any tutorial for rest with OAuth ?

  • rajan

    Thanks for this tutorial …What table structure i need to have to in my localhost before executing the restful services given ?

  • Right now it appears like Drupal is the top blogging platform available right now.

    (from what I’ve read) Is that what you’re using on your blog?

  • There was one error in the project, the init-param was org.conraets and produced a container expection. When I changed that to it worked like a dream. google

  • thanks for the post!!!!!!!!!!

  • ali khan

    SEO support from a organization that is qualified in the solutions so it provides. There are a wide range of SEO organizations out there, yet very several of these organizations has been targeted at supplying the people with highest possible value for cash. additional info read

  • Very good sample and explanation…

  • it doesnt show particular empoyee details

  • Imtiaz

    I want to open this project in NET beans IDE 8.0.2 but not able to import it. Please can you help me to know how to import this project in netbeans.

  • Do I have deploy separately? How can I deploy restful web services?

  • Fabrics we use in our form; The first-class micro-interlock; flex-fit, anti-bacterial, it has a thermo-balance, and immediately drying. This gives you the freedom to move your soccer jerseys of the match; It is designed stylish enough to be worn on a daily basis. Our models are produced in two types as my special jerseys and other digital printed.

  • başarılı bir site ücretsiz backlink ekleyin

  • Pingback: java - Access-Control-Allow-Origin in chiamata ajax jersey di servizi web rest()

  • Pingback: java - Access-Control-Allow-Origin en appel ajax de maillot de services web rest()

  • Pingback: java - Access-Control-Allow-Origin en la llamada ajax a jersey de servicios web rest()

  • yuvaraj singh

    Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Product Management Launchpad during this lockdown period everyone can use it wisely.
    Product Management Workshop