Monday, November 5, 2012

Java Restful Web Services(JAX-RS) Using Jersy

This tutorial demonstrates how to build a Java Restful web service in Eclipse using Jersy plugin.

Download project

REST(Representational State Transfer) is an architectural style. This is not a standard whereas SOAP is standardized. RESTful web services are based on HTTP protocol and its methods PUT, GET, POST, and DELETE. They do not require XML SOAP messages or WSDL service definitions.

REST can be considered similar to a client-server architecture. There 's a REST server waiting for the requests from REST clients.

Requirements :

Main Topics



  1. Install Jersy plugin

  2. Create resource

  3. Create client

  4. Configure web.xml



1. Install Jersy plugin


Create new dynamic web project. Add  following jars from the downloaded Jersey zip file to WEB-INF/lib. Add them to project Build Path.

1. Create resource


[sourcecode language="java"]
package com.res;

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

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

// This method is called if TEXT_PLAIN is request
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersey";
}

// This method is called if XMLis request
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}

// This method is called if HTML is request
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}

}
[/sourcecode]

3. Create client


[sourcecode language="java"]
package com.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
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 client {

/**
* @param args
*/
public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
// Fluent interfaces
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());
// Get plain text
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));
// Get XML
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_XML).get(String.class));
// The HTML
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_HTML).get(String.class));
}

private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8440/Success").build();
}

}
[/sourcecode]

4. Configure web.xml


[sourcecode language="java"]
<?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">
<display-name>Success</display-name>
<servlet>
<servlet-name>Jersey 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>com.res</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
[/sourcecode]

web.xml is tricky!
[Extracted from : http://www.javahotchocolate.com/tutorials/restful.html]
The display name. It can be anything, but it's

what goes first thing in the URL (browser address

line) after the protocol (http) and domain-

name:port-number. Note that I'm not using

anything that looks like a package name here. I

don't even have to use the Eclipse project name.

Obviously, it cannot contain a space.

The servlet name. It can have spaces in it, but it's

used in another place and the two must be identical.

The servlet name doesn't show up outside this file,

but this file uses it to find the appropriate mapping

definition.

The servlet container class. This pertains to the

framework you're using. Here, we're using Jersey, so

we're sure to name that class which comes out of

the user library (set of Jersey JARs) we used.

The servlet container class parameter name, as

dictated (in this instance) by the REST servlet

container or framework in use.

The value of the preceding parameter. It must be

the package name that contains at least and at most

one (JAXB) servlet (.java file). There may be more

than one such servlet, but if so, the other(s) must be

in a different Java package.

The servlet name must be identical to the one

already specified above. As noted, if there are two

servlets, there are two servlet definitions and two,

separate servlet mapping definitions.

The URL pattern. It starts with '/' and ends with

'/*' and can be any legitimate directory-like

identifier (without spaces). It is the penultimate

element of the URL, just before the class name path.

web.xml:




Fun



Jersey REST Service
com.sun.jersey.spi.container.servlet.ServletCo

ntainer

com.sun.jersey.config.property.packages


de.vogella.jersey.first

1




Fun with REST
com.sun.jersey.spi.container.servlet.ServletCo

ntainer

com.sun.jersey.config.property.packages


com.etretatlogiciels.fun

1




Jersey REST Service
/rest/*



Fun with REST
/fun/*


2 comments:

  1. Excellent pieces. Keep writing such kind of info on your page.
    Im really impressed by your blog.
    Hey there, You've done a fantastic job. I'll certainly digg it and in my opinion suggest to my friends.
    I'm confident they will be benefited from this web site.

    ReplyDelete
  2. Hi,
    Thank you for commenting this tutorial.

    ReplyDelete

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...