Make everything as simple as possible, but not simpler. -Albert Einstein 

formats

How to Build a RESTful Web Service with Jersey

Summary: In this post, we will implement RESTful style web services using Jersey. Jersey is an open source, production grade, JAX-RS (JSR 311) Reference Implementation for building RESTful web services.  RESTful style web services was first introduced in Roy Fielding’s research paper,  “Architectural Styles and the Design of Network-based Software Architectures” in 2000.  As a result of its simplicity, RESTful style web services have become  the preferred web service design model.

Prerequisites: If you would like to obtain this article’s complete sample, it may be obtained from our GitHub repository. All samples are Maven based java projects.  In addition, this article will require that you have Apache Tomcat 6.x installed.

Let’s Get Started! Representational State Transfer (REST) is an architectural design principle in which the web services are viewed as resources.  In addition, these services are uniquely identified by URLs.  One important principal of RESTful webservices is the use of HTTP methods to represent the invocation of different operations.

RESTFul  design principle utilizes  HTTP protocol methods for processing CRUD operations:

      POST – Create a resource

      GET – Retrieve a resource

      PUT – Update a resource

      DELETE – Delete a resource

Please refer to Listing 1: HelloWorldService.java for the following:

In line 15, The @Path annotation specifies the URI of a resource

In line 18, The @Get annotation maps the  sayHello() operation to the  HTTP  GET request.

In line 19, The @Path  annotation combined with the root path “/helloworld”  forms the sub resources’ URI.

In line 20, The @Produces annotation defines the response content MIME type as plain/text.

In line 21,  The @QueryParam annotation is used bind the value of a URI’s parameter to a method’s parameter.

Listing 1: HelloWorldService.java

package techbysample.jersey.sample1;

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

/**
*
* @author TechBySample.com
*
*/

@Path("/helloworld")
public class HelloWorldService {

@GET
@Path("/sayhello")
@Produces( MediaType.TEXT_PLAIN)
public String sayHello(@QueryParam("message")  String msg) {
String output = "Hello " + msg;
System.out.println(output);
return output;
}

}

Deploying the RESTFul web service:

Change directory to the project’s root folder.

Follow these steps:

1.  Type:
mvn package

2. Next, simply copy the  .war  file to Apache Tomcat’s  webapps folder.

Testing RESTFul web service:

From the ‘jersey-sample1′ project directory, type:

mvn -Dtest=TestHelloWorldService test -DWEB_SERVICE_HOST=<host> -DWEB_SERVICE_PORT=<port>

You should see a result similar to the following output:

——————————————————-
T E S T S
——————————————————-
Running techbysample.jersey.sample1.TestHelloWorldService
Hello Techbysample.com
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.58 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ———————————————————————–
[INFO] BUILD SUCCESS
[INFO] ———————————————————————–
[INFO] Total time: 3.236s
[INFO] Finished at: Sun Aug 19 16:05:15 CDT 2012
[INFO] Final Memory: 3M/7M
[INFO] ———————————————————————–

Please refer to Listing 2: TestHelloWorldService.java for the following:

In lines 51-59, The statements are used to construct an url that resembles:

http://localhost:8080/jersey-sample1/rest/helloworld/sayhello?message=hello

Listing 2: TestHelloWorldService.java

package techbysample.jersey.sample1;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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;
import com.sun.jersey.core.util.MultivaluedMapImpl;
/**
 *
 * @author TechBySample.com
 *
 */

public class TestHelloWorldService{

	private String hostName =null;
	private String port = null;

	@Before
	public void initialize() throws Exception {

		hostName = System.getProperty("WEB_SERVICE_HOST");
		port = System.getProperty("WEB_SERVICE_PORT");

		if (hostName==null)
		{
			hostName = "localhost";
			System.out.println("No webservice host specified using default");
		}
		if (port==null)
		{
			port = "8080";
			System.out.println("No webservice port specified using default");
		}
	}

	@Test
    public void testHelloWorld()
	{
		try{
			ClientConfig config = new DefaultClientConfig();
			Client client = Client.create(config);

			WebResource webResource = client.resource(getBaseURI());

			MultivaluedMap queryParams = new MultivaluedMapImpl();
			queryParams.add("message", "Techbysample.com");

			webResource = webResource.path("helloworld").path("sayhello").queryParams(queryParams);

			String response = webResource.accept(MediaType.TEXT_PLAIN).get(String.class);

		    System.out.println(response);

			}
			catch (Exception e)
			{
				System.out.println("Error" + e);
			}
	}

	private URI getBaseURI() {

		StringBuffer sbUrl = new StringBuffer();
		sbUrl.append("http://");
		sbUrl.append(hostName);
		sbUrl.append(":");
		sbUrl.append(port);
		sbUrl.append("/jersey-sample1/rest");

		return UriBuilder.fromUri(
				sbUrl.toString()).build();
	}

    @After
	public void cleanup()
	{
    	 hostName =null;
    	 port = null;
	}
}

Resources:

Official Jersey REST website

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
© Techbysample.com, all rights reserved.