Monday, March 10, 2014

Getting started with RESTful webservice using Jersey

Jersey helps developing RESTful webservices seamlessly and makes your life easy. This article gives you a quick start on how to create your first RESTful web service using Jersey & Maven.  I assume you have a decent understanding of maven and J2EE.

Make sure you have
  1. Eclipse Kepler
  2. M2Eclipse plugin
  3. Java 1.7
  4. Tomcat 7
Step 1 - Maven Project
Create a new maven project from your eclipse.  Select maven-archetype-webapp archetype,  provide group id, artifact id, package in the following dialog. (See screenshot below)

Note: By default installed facets will not be Java 1.7, Dynamic web module 2.4.  You can edit this in org.eclipse.wst.common.project.facet.core.xml under .settings folder.  Also make sure to change the JRE from 1.5 to 1.7 in your project build path.

Step 2 - Maven Dependencies
Add the following jersey server and jersey servlet dependencies to your pom.xml
Step 3 - Deployment Descriptor
Add the Jersey servlet container to your web.xml.
Step 4 - REST Resource
Create your package and SampleRestResource class.  Add the path "/sample" at the class level, and add 2 GET resources. One with path "/hello" and the other with "/hello/{message}".  
Step 5 - Run your application
Right click on your project --> Run As --> Run on Server --> Select tomcat.  Now your first resource can be accessed from http://localhost:8080/jersey-rest-helloworld/jersey/sample/hello and the other resource from http://localhost:8080/jersey-rest-helloworld/jersey/sample/hello/your%20message

You can download the complete source here.

No comments:

Post a Comment