Wednesday, January 18, 2012

A simple jersey application

Create a new web application and  add jersey-core-1.1.5.jar, jersey-server-1.1.5.jar, jersey-client-1.1.5.jar, jsr311-api-1.1.1.jar, asm-3.1.jar  to WEB-INF/lib.


package com.mycompany.rest;

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

@Path("/helloWorld")
public class HelloWorld {

  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public String plainHelloWorld() {
    return "Hello World";
  }

    @GET
    @Produces(MediaType.TEXT_XML)
    public String xmlHelloWorld() {
        return "<?xml version=\"1.0\"?>" + "<hello> Hello World </hello>";
    }
   
   
   
@GET
   @Produces(MediaType.TEXT_HTML)
    public String htmlHelloWorld() {
        return "<html> " +  "<body>" + "Hello World" + "</body>" + "</html> ";
    }

}

The client to test the service

package com.mycompany.rest;

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;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

public class RestClient {
    public static void main(String[] args) {
        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
                //Http basic authentication  
        client.addFilter(new HTTPBasicAuthFilter("username","password"));
        WebResource service = client.resource(UriBuilder.fromUri( "http://localhost:9085/testapplication").build());
       
        System.out.println(service.path("rs").path("helloWorld").accept(
                MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());
        // Get plain text
        System.out.println(service.path("rs").path("helloWorld").accept(
                MediaType.TEXT_PLAIN).get(String.class));
        // Get XML
        System.out.println(service.path("rs").path("helloWorld").accept(
                MediaType.TEXT_XML).get(String.class));
        // Get HTML
        System.out.println(service.path("rs").path("helloWorld").accept(
                MediaType.TEXT_HTML).get(String.class));

    }
}

In web.xml:
 
<servlet>
   <servlet-name>RESTFUL SERVICE</servlet-name>
   <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>
   
<servlet-mapping>
    <servlet-name>RESTFUL SERVICE</servlet-name>
    <url-pattern>/rs/*</url-pattern>
</servlet-mapping>
   

The endpoint you are looking for is http://localhost:9085/testapplication/rs/helloWorld


No comments:

Post a Comment