Friday, June 1, 2012

Implement RESTful Web Services using Jersey

Jersey Overview

Jersey is the open source, production quality, JAX-RS (JSR 311) Reference Implementation for building RESTful Web services. Jersey is very lightweight and can be deployed in Web application containers like Tomcat, Jetty, Glassfish.

In this blog, we will provide a comprehensive tutorial on how to create a RESTful web services using Jersey, including,
  • Support for HTTP method, GET, PUT, POST, and DELETE
  • Support for various content types including TEXT, XML, and HTML
  • JSON support

Develop RESTful Web Services using Eclipse

We will demonstrate how to develop web services in Jersey using Eclipse. in the following steps,
  1. Create a new Dynamic Web Project in Eclipse
  2. Import Jersey related libraries
  3. Configure web.xml to support Jersey
  4. Create a Java class that implements Web Services
  5. Deploy web project in Tomcat
  6. Start Tomcat and test

Configure Tomcat to enable access log logging

We need to enable Tomcat to log accesses for easy debugging. Uncomment the following block in Tomcat's server.xml file,
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="common" prefix="localhost_access_log." resolveHosts="false" suffix=".txt"/>

Configure web.xml to support Jersey

Here is a sample web.xml file, which includes JSON support and auto scanning of Java package jersey.cors. Replace package name "jersey.cors" with one's own package.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <servlet>
    <servlet-name>Jersey Root REST Service</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>jersey.cors</param-value>
    </init-param>
 <init-param>
  <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
  <param-value>true</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Root REST Service</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

Create a Java Class that Implements Web Services


package jersey.cors;

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

// POJO, no interface no extends

// The class registers its methods for the HTTP GET request using the @GET annotation. 
// Using the @Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML. 

// The browser requests per default the HTML MIME type.

//Sets the path to base URL + /hello
@Path("/hello")
public class HelloWorldRest {

 @GET
 @Path("/{param}/")
 public String getMsg(@PathParam("param") String msg) {
 
  String output = "Jersey say : " + msg;
 
  return output;
 
 }
 @GET
 @Path("/world")
 public String getFixedMsg(String msg) {
 
  String output = "Jersey say : fixed path" + msg;
 
  return output;
 
 }
 // This method is called if TEXT_PLAIN is request
 @GET
 //@Path("helloworld")
 @Produces(MediaType.TEXT_PLAIN)
 public String sayPlainTextHello() {
  System.out.println("sayPlain");
  return "Hello Jersey";
 }

 // This method is called if XML is request
 @GET
 //@Path("helloworld")
 @Produces(MediaType.TEXT_XML)
 public String sayXMLHello() {
  System.out.println("sayXML");
  return "" + " Hello Jersey" + "";
 }

 // This method is called if HTML is request
 @GET
 //@Path("helloworld")
 @Produces(MediaType.TEXT_HTML)
 public String sayHtmlHello() {
  System.out.println("sayHTML");
  return "<html> " + "<title>" + "Hello Jersey" + "</title>"
    + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
 }
 
 // This method is called if JSON is request
 @GET
 //@Path("helloworld")
 @Produces(MediaType.APPLICATION_JSON)
 public Hello sayJsonHello() {
  return new Hello("Hello", "Jersey");
 }
        @PUT
 @Produces(MediaType.APPLICATION_JSON)
 public Hello updateHello(Hello hello)
 {
  System.out.println("put");
  return hello;
 }
 @POST
 @Produces(MediaType.APPLICATION_JSON)
 public Hello createHello(Hello hello)
 {
  System.out.println("post");
  return hello;
 }
 @DELETE
 @Produces(MediaType.APPLICATION_JSON)
 public Hello deleteHello(Hello hello)
 {
  System.out.println("post");
  return hello;
 } 
 @DELETE
 @Produces(MediaType.TEXT_PLAIN)
 public String deleteHello(String hello)
 {
  System.out.println("post");
  return hello;
 } 
}
Here is the Hello class, which serves as JSON transport object.
package jersey.cors;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Hello {
 String greeting;
 String name;
 public Hello()
 {
  
 }
 public Hello(String greeting, String name)
 {
  this.greeting = greeting;
  this.name = name;
 }
 public String getGreeting() {
  return greeting;
 }
 public void setGreeting(String greeting) {
  this.greeting = greeting;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 
} 

Testing Web Services

After web service project is deployed in Tomcat, we should be able to start Tomcat with no error.
Generally, Web Services can be tested in the following manner,
  • HTTP GET method can be tested directly through a browser
  • HTTP GET, PUT, DELETE, and POST can be tested through Java script
  • HTTP GET and POST can be tested through Jersey client. (Due the limitation in Java URLConnection class, it can be challenging to test HTTP PUT and DELETE using Jersey client). 

Javascript Example

 Here is an Javascript HTTP DELETE example, with JSON support,
<html> 
<head> 
<title>Cors Example</title> 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="log4javascript.js"></script>
<script> 
var hello = JSON.stringify({"greeting":"Hello","name":"jersey"});
//alert(hello);
$(document).ready(function() {

 //alert('before ajax call');
 $.ajax({
  headers: {
   Authentication : 'Bearer access_token'
  },
  
  //this is the php file that processes the data and send mail
  //url: "http://localhost:8080/cxf-hello-cors/rest/annotatedGet/hello", 
  //url: "http://localhost:8080/cxf-hello-cors/service1/time", 
  // url: "http://localhost:8080/resteasy/tutorial/helloworld",
  url: "http://localhost:8080/jersey/hello",
  
  contentType: "application/json",

  //GET method is used
  type: 'DELETE',
  
  //pass the data         
  dataType: 'json',   
   
  //data: JSON.stringify(hello), 
  data: hello,
  
  //Do not cache the page
  cache: false,
   
  //success
  success: function (html) {  
   //alert(html); 
   document.getElementById("cors").innerHTML = "Echo: " + html.greeting + "," + html.name; 
           
  } ,
  error:function (data, status) {
   alert(data);
   alert(status);
     }      
 });
     
 });
</script>
</head> 
<body> 

<h1>This is the CORS test page</h1>

<p>Hello, <div id="cors"/>

</body> 
</html>

Jersey Client Example 

Here is a HTTP GET Jersey client example,
package jersey.cors.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
 
public class JerseyClient {
 
  public static void main(String[] args) {
 try {
 
  Client client = Client.create();
 
  WebResource webResource = client
     .resource("http://localhost:8080/jersey/hello");
  
  ClientResponse response = webResource.accept("application/json")
                   .get(ClientResponse.class);
 
  if (response.getStatus() != 200) {
     throw new RuntimeException("Failed : HTTP error code : "
   + response.getStatus());
  }
 
  String output = response.getEntity(String.class);
 
  System.out.println("Output from Server .... \n");
  System.out.println(output);
 
   } catch (Exception e) {
 
  e.printStackTrace();
 
   }
 
 }
}



 

 

1 comment: