Monday, April 29, 2013

create restful web service using eclipse

In this article I would like to explain the creation of sample restful service,  
Tools used,

  • Eclipse Indigo
  • Maven build tool
Create restful web service using jersey.

We have to install maven plugins in Eclipse to start, follow the below section to install maven tool in Eclipse.

Install maven tool

  • Also add Maven Integration for Eclipse WTP using the repository select only ‘Maven Integration for Eclipse WTP’ and install

In order to set local maven repository go to the workspace and run the command
mvn -Declipse.workspace= eclipse:add-maven-repo
if the above command is not working, set the maven_home appropriately in the environment variable.

Create Project
Now you have to go and create a new project in the Eclipse. Go New=>project=>Maven Project=> and click next in the final window give as given in the window
In the final step you can provide as follows
Now you can remove the junit test classes and packages if you want and you can make the changes in the generated package and class.

Create a restful web service.

You can create a restful service class as given below.
package com.smashplus;

public class TestRest {
public Response getMsg(@PathParam("name") String name) {

String output = "Hello, " + name;

return Response.status(200).entity(output).build();
In the above class we used following annotations. 

@Path(path) annotation Sets the path to base URL + /path provided. The base URL is based on your application name, the servlet and the URL pattern from the web.xml" configuration file.

@PathParam : Used to inject parameter values from the URL into a method parameter. This way we can inject values like ID to pass to the restful service.

@Get : GET Request

Then we need to add the web.xml file, This will have the mapping to the corresponding restful service class. Here if the request comes matches with the path  /resources/*  it will redirect to the jersey servlet and jersey container will find appropriate resource class available in the mentioned package here it is com.smashplus and the resource class is TestRest. Web.xml file should add in to the path src\main\webapp\WEB-INF\.

<web-app id="WebApp_ID" version="2.4" xmlns:xsi="" xmlns="" xsi:schemalocation="">
 <display-name>Restful Web Application</display-name>




final pom.xml file will look like as follows
..code excluded..
...code excluded..
Now you can deploy the war file to the server. I am using Tomcat 6.0 for the deployment, and visit below service URL http://localhost:8080/restdemo/resources/test/Smashplus

The output will be,

Hello, Smashplus
Download Souce code(select File=>Download)