Sunday, August 28, 2011

Simple Jersey

  1. Download the jersey.zip file from (http://download.java.net/maven/2/com/sun/jersey/jersey-archive/1.8/jersey-archive-1.8.zip)
  2. nzip jersey-archive-1.8.zip and import all the jar files contained lib folder.
  3. Create Hello.java:
  • import javax.ws.rs.GET;
  • import javax.ws.rs.Path;
  • import javax.ws.rs.Produces;
  • import javax.ws.rs.core.MediaType;
  • @Path("/hello")
  • public class Hello {
  •     // This method is called if TEXT_PLAIN is request
  •     @GET
  •     @Produces(MediaType.TEXT_PLAIN)
  •     public String sayPlainTextHello() {
  •         return "Hello World";
  •     }
  •     // This method is called if XML is 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 World" + "</title>"
  •                 + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
  •     }
  • }

4. In web.xml, add the following context:
  • <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>JerseyTest</display-name>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
        </welcome-file-list>
        <display-name>Jersey Service</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.cht.paas.jersey</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>
5. start your tomcat server and enter the url:  http://localhost:8080/JerseyTest/rest/hello
References:
  1. http://www.vogella.de/articles/REST/article.html#first_project
  2. http://jersey.java.net/nonav/documentation/latest/user-guide.html#chapter_deps

No comments:

Post a Comment