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:

<servlet>
	<servlet-name>Jersey</servlet-name>
	<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
	<init-param>
		<param-name>com.sun.jersey.config.property.packages</param-name>
		<param-value>org.coenraets</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
	<servlet-name>Jersey</servlet-name>
	<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

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:

package org.coenraets.directory;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/employees")
public class EmployeeResource {

	EmployeeDAO dao = new EmployeeDAO();

	@GET
	@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:

http://coenraets.org/rest/employees
http://coenraets.org/rest/employees//1
http://coenraets.org/rest/employees/1/reports

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 http://coenraets.org/rest/employees -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).

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

  1. Mario Junior November 11, 2011 at 2:00 pm #

    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.

  2. Mario Junior November 13, 2011 at 8:52 am #

    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.
    http://blog.dclick.com.br/2011/11/13/amfrestfull-um-back-end-para-qualquer-front-end/pt/ (in portguese).

    Best Regards.

  3. leo May 18, 2012 at 3:44 pm #

    Brilliant tutorial, many thanks!

  4. Kamal September 5, 2012 at 1:29 am #

    Hi,
    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.

  5. Kris October 26, 2012 at 1:55 pm #

    Hi,

    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?

    Kris

  6. Alexk2009 November 21, 2012 at 8:43 pm #

    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 org.conraets.directory it worked like a dream. Not one of my favourite dreams, but good enough. Thanks for this

  7. ryan November 28, 2012 at 8:24 am #

    Hi,

    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?

    thanks
    ryan

  8. Bob March 20, 2013 at 1:50 pm #

    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.

  9. asma March 22, 2013 at 9:37 am #

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

    thanx
    asma

  10. asma March 22, 2013 at 9:38 am #

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

    thanks
    asma

  11. Paul March 28, 2013 at 11:19 am #

    Thanks for the example.

  12. Amol Powar May 28, 2013 at 3:49 pm #

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

  13. rajan November 5, 2013 at 3:21 am #

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

  14. webrtc demo July 18, 2014 at 11:37 pm #

    Selecxt a title for the library that you simply strategy to share around tthe hoise network.
    Wylder is a part time freelancer and amateur author. It would be more proftable
    and appealing for the users and they would bbe able to understand the information on it in a more easy
    way.

  15. Guadalupe July 21, 2014 at 7:33 pm #

    Do you mind if I quote a few of your posts as long as I
    provide credit and sources back to your webpage? My blog is in the exact
    same niche as yours and my users would certainly benefit from some of the information you provide here.

    Please let me know if this okay with you. Regards!

  16. bikes for toddlers July 23, 2014 at 5:15 am #

    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?

  17. south jersey gutter cleaning July 25, 2014 at 4:24 am #

    Can I simply say what a relief to discover somebody that actually understands what they are
    discussing over the internet. You definitely understand how to bring a problem to light
    and make it important. A lot more people have to look at this
    and understand this side of your story. It’s surprising you’re not more popular since you certainly possess the gift.

  18. http://www.wardsorientalrugservice.com/ July 30, 2014 at 10:49 am #

    I visited many websites еxcept the audio feature fօr audio sonjgs current at this web site
    іs in faϲt fabulous.

  19. big wheels for kids July 31, 2014 at 10:57 am #

    Hi there, everything is going nicely here and ofcourse every one is sharing facts, that’s truly fine, keep up writing.

Trackbacks/Pingbacks

  1. Random Code » De un programador a otro programador » Crear un servidor REST con Jersey - January 20, 2012

    [...] tutorial esta basado en el articulo “Building RESTful Services with Java Using JAX-RS and Jersey” por Christophe [...]

Leave a Reply