Wednesday, January 18, 2012

Jersey-Spring Integration

If you don't plan to use spring, look at a simple Jersey application without spring integration here

This article shows basic code to integrate spring with Jersey. Jersey has the ability to convert a JAXB annotated class to xml. This code is also included.

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, jersey-spring-1.1.5, ,jaxb-api-2.2.jar,jaxb-impl-2.2.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;
import org.springframework.stereotype.Component;

@Component
@Path("/helloWorld")
public class HelloWorld {
 @GET
 @Produces(MediaType.TEXT_PLAIN)
 public String plainHelloWorld() {
   return "Hello World";
 }

@GET
@Produces(MediaType.TEXT_XML)
public Person sayXMLHello() {
   Person person = new Person();
   person.setAge(29);
   person.setFirstName("harish");
   person.setLastName("Choragudi");
   return person;
 }

@GET
@Produces(MediaType.TEXT_HTML)
public String htmlHelloWorld() {
  return " " +  "" + "Hello World" + "" + " ";
}
}


package com.mycompany.rest;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
   private String firstName;
   private String lastName;
   private Integer age;
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public Integer getAge() {
    return age;
}
public void setAge(Integer age) {
    this.age = age;
}
 
}


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
<context-param>
        <description></description>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

       
<listener>
        <description></description>
        <display-name>AppInit</display-name>
        <listener-class>
              org.springframework.web.context.ContextLoaderListener
        </listener-class>
</listener>

<servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>
              com.sun.jersey.spi.spring.container.servlet.SpringServlet
        </servlet-class>
       <init-param>  
          <param-name>  
            com.sun.jersey.config.property.resourceConfigClass   
          </param-name>    
          <param-value>  
             com.sun.jersey.api.core.ClasspathResourceConfig   
          </param-value>  
       </init-param>  
       <init-param>  
         <param-name>  
            com.sun.jersey.config.property.classpath   
         </param-name>    
         <param-value>
            WEB-INF/lib
         </param-value>  
    <!-- Use WEB-INF/lib if you have your Service class in a jar file. 
      WEB-INF/classes is used if you have your service classes in class folder 
      of your web application  
    -->
       </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>


If you don't have   com.sun.jersey.config.property.resourceConfigClass  param value set the exception below is thrown. So make sure you set it.
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not
contain any root resource classes.
If you use spring  make sure you use <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class> instead of  <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> 

No comments:

Post a Comment