Sunday, 25 January 2015

JAX-RS Annotations and First Program Example 1



JAX-RS is a Java programming language API designed to make it easy to develop applications that use the REST architecture.

The JAX-RS API uses Java programming language annotations to simplify the development of RESTful web services

There are 11 Annotations.



In this example we are going to see following annotations.

@Path
@GET
@Produces

Example:
package com.sun.jersey.samples.helloworld.resources;

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

// The Java class will be hosted at the URI path "/helloworld"
@Path("/helloworld")
public class HelloWorldResource {
    
    // The Java method will process HTTP GET requests
    @GET
    // The Java method will produce content identified by the MIME Media
    // type "text/plain"
    @Produces("text/plain")
    public String getHelloMessage() {
        // Return some cliched textual content
        return "Hello World";
    }
}



Explanation:
  1. HelloWorldResource Class is a  root resource class.
    Root resource classes
     are POJOs that are either annotated with @PATH or have at least one method annotated with @Path or a request method designator, such as @GET, @PUT, @POST, or @DELETE. Resource methods are methods of a resource class annotated with a request method designator.
  2. @Path("/helloworld") : The Java class will be hosted at the URI path "/helloworld"
    URI path would be http://localhost:8080/helloworld/ OR 
    http://myservice.com/helloworld/(could be called from browser, we will see how later)
  3. @GET - the annotated Java method will process HTTP GET requests.
  4. @Produces  - annotation specifies the MIME media types, a resource can produce and send back to the client. 
    MIME (Multi-Purpose Internet Mail Extensions) is an extension of the original Internet e-mail protocol that lets people use the protocol to exchange different kinds of data files on the Internet: audio, video, images, application programs, and other kinds

    In this example, the Java method getHelloMessage() will produce representations identified by the MIME media type "text/plain", which is  returning value 
    "Hello World"


Responding to HTTP Methods and Requests
The behavior of a resource is determined by the HTTP methods (typically, GET, POST, PUT, DELETE) to which the resource is responding.


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home