Saturday, October 20, 2012

Build a RESTful Web service with Java

Representational state transfer (REST) is a architectural style of designing loosely coupled applications based on web-standards and the HTTP protocol. It relies on a stateless, client-server, cacheable communications protocol -- and in virtually all cases, the HTTP protocol is used.The hardest part of building a RESTful application is deciding on the resources you want to expose. Once you've done that, using the open source Restlet framework makes building RESTful Web services a snap. This tutorial guides you step-by-step through the fundamental concepts of REST and building applications with Restlets.

Step 1: Create a dynamic web project in Eclipse and add the jars shown in the figure in the lib folder under the WEB-INF

Step 2: Add the Restful nature in the the project using fallowing entry in the web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">

Step 3:Create the Employee class as fallows and annotted it with the @Path,@Produce and @Get annotations
package com.rajkrrsingh.blogspot;


public class Employee {
 public String getEmployee(){
  return "<html> " + "<title>" + "Employee Details" + "</title>"
          + "<body><h1>" + "Employee Name is Dummy Employee" + "</body></h1>" + "</html> ";


Step 4: now run the dynamic web application on the tomcat server and access the fallowing URL


Here is the browser output

Step 5:you can use jersy api or Apache HttpClient api to the test the webservice by creating a client,here I have created the client using the jersy api

package com.rajkrrsingh.blogspot.client;



import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class Main {
 public static void main(String[] args) {
  ClientConfig config = new DefaultClientConfig();
     Client client = Client.create(config);
     WebResource service = client.resource(getBaseURI());
 private static URI getBaseURI() {
     return UriBuilder.fromUri("http://localhost:8080/RESTfulProject").build();


After running this main class as a java application you will find the fallowing output on the console

<html> <title>Employee Details</title><body><h1>Employee Name is Dummy Employee</body></h1></html>