Tuesday, 14 May 2013

RESTFUL Web Service Basic Program using Jersey (JAX-RS)


Hi Friends,
I would like to share a simple Hello World program in Restful web services.

Here to implement JAX-RS am using Jersey, which is well matured and production quality implementated api.

In Restful Web services, the response provided by the service to a class is the Resource class.
These Root Resource classes are the POJO classes which are annotated with @Path.

These resources should contains atleast one resource method designator annotation such as
@Get
@Post
@Put
@Delete

Commonly mostly used among those are @Get and @Post.

@Path annotation's value is a relative URI path.

The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client.
It can be applied at both class and method levels.
More than one media type may be declared in the same @Produces declaration.

The  @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client.
It can be applied at both class and method levels.
More than one media type may be declared in the same @Consumes declaration.


Following is the basic Hello World Program for Restful Web services (JAX-RS)


@Path("/hello")
public class Hello {
    @GET
    @Produces({MediaType.TEXT_HTML,MediaType.TEXT_PLAIN})
    public String sayHello() {
        String resp =  "<html><head><title>Hello World</title></head>"
   + "<body><h1>Hello World!</h1></body></h1></html> ";
return resp;
    }
}

Check the Deployment of RESTFUL WEB SERVICES here.

After successful deployment, check the service.

Sample URL is:
http://ipaddress:port/context-path/jersey-servlet-path/hello
(relative path is /hello)

The Restful service @Produces will choose the most acceptable media type as declared by the client.

For example if the Accept header is:
Accept: text/plain
then the total HTML content will be displayed as Plain Text as

<html><head><title>Hello World</title></head><body><h1>Hello World!</h1></body></h1></html> 

Alternatively if the Accept header is:
Accept: text/plain;q=0.9, text/html
which declares that the client can accept media types of "text/plain" and "text/html" but prefers the latter, then the HTML Page will be rendered as

Hello World!



No comments:

Post a Comment