Tomcat embedded with JAX-RS Jersey

Introduction

This tutorial will show how to setup Tomcat 8.0 with Jersey and running restful application from an embedded mode.

 

Developer Sandbox

  • Windows 7 64 bit
  • Tomcat 8.0 Embedded
  • Jersey 2.6
  • Eclipse Juno

 

Steps

I will explain two ways of deploying a Jersey rest application. The first one will use web.xml. The second example will use ResrouceConfig class.

Download Libraries

Download Tomcat 8 Embedded

  • Unzip to a location like C:\LIBS_and_Jars\tomcatembeddedjars
Tomcat JARs
Tomcat JARs

Download Jersey 2.6

Maven will be used to download Jersey and dependent jars. Manually downloading jars is a pain. Here I’ll explain how to use Maven just as a downloading and dependency management tool.

  • Create a folder like C:\LIBS_and_Jars\jerseyjars
  • Assuming you have maven installed, open up a command prompt.
  • CD to C:\LIBS_and_Jars\jerseyjars
  • Issue the following mvn command

mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes  -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.6 -DgroupId=com.example -Dpackage=com.example -Dversion=1.0 -DinteractiveMode=false -DartifactId=jersey-basic-2.6

  • A folder named jersey-basic-2.6 should be created like C:\LIBS_and_Jars\jerseyjars\jersey-basic-2.6
  • Change directory to jersey-basic-2.6
  • Now issue the following maven command to put all jersey and dependent jars into one location at target\dependency.

mvn dependency:copy-dependencies

  • All jars should be copied over to a folder like C:\LIBS_and_Jars\jerseyjars\jersey-basic-2.6\target\dependency
Jersey JARs
Jersey JARs

Setup Eclipse Project

  •  Start new Eclipse project of type “Java”.
  • Add all jars that were downloaded in previous steps as External JARs.
  • Start adding Java sources as stated in next step.
Java Build Path
Java Build Path

 

 

HelloWorldRestResource.java

First a very basic Jersey resource.


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 HelloWorldRestResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello() {
        return "Hello World from Tomcat Embedded with Jersey!";
    }
}

 

ResourceLoader.java

Now let us write a Jersey resource loader class that will register a restful Java resource. In this example the resource loader will load HellowWorldRestResource.


import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

public class ResourceLoader extends Application{

    @Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> classes = new HashSet<Class<?>>();
       
        // register root resource
        classes.add(HelloWorldRestResource.class);
        return classes;
    }
}

 

Main.java with web.xml

Now we are going to write the Main.java which will be responsible for starting embedded Tomcat. In the first version of Main.java I’ll show how to register the resource loader using a traditional web.xml. First the Main.java source file.


import javax.servlet.ServletException;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.Context;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import java.io.File;
import java.net.MalformedURLException;

public class Main {

    public static void main(String[] args) throws Exception, LifecycleException {
        new Main().start();
    }

    public void start() throws ServletException, LifecycleException,
            MalformedURLException {

        // Define a folder to hold web application contents.
        String webappDirLocation = "WebContent/";
        Tomcat tomcat = new Tomcat();

        // Define port number for the web application
        String webPort = System.getenv("PORT");
        if (webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }
        // Bind the port to Tomcat server
        tomcat.setPort(Integer.valueOf(webPort));

        // Define a web application context.
        Context context = tomcat.addWebapp("/tomcatembedded", new File(
                webappDirLocation).getAbsolutePath());

        // Define and bind web.xml file location.
        File configFile = new File(webappDirLocation + "WEB-INF/web.xml");
        context.setConfigFile(configFile.toURI().toURL());

        tomcat.start();
        tomcat.getServer().await();
    }

}

Now the web.xml.

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<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_3_0.xsd" id="WebApp_ID" version="3.0">
 
  <servlet>
    <servlet-name>REST Servlet</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>ResourceLoader</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>REST Servlet</servlet-name>
    <url-pattern>/resourceloader/*</url-pattern>
  </servlet-mapping>
    
</web-app>

Here is an overview of folder and file structure to show where to put web.xml file in the Eclipse project

Eclipse Folder Structure
Eclipse Folder Structure 

 

Test the REST Resource

Use a browser to test out the REST resource using this url

http://localhost:8080/tomcatembedded/resourceloader/helloworld

This should display the following page as shown here.

Browser page
Browser page 

 

Main.java using ResourceConfig() no web.xml

Please notice that I’ve taken out reference to web.xml and instead using resourceConfig() to load a servlet container which in turn loading the ResourceLoader.java.


import javax.servlet.ServletException;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.Context;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import java.io.File;
import java.net.MalformedURLException;

public class Main {

    public static void main(String[] args) throws Exception, LifecycleException {
        new Main().start();
    }

    public void start() throws ServletException, LifecycleException,
            MalformedURLException {

        // Define a folder to hold web application contents.
        String webappDirLocation = "WebContent/";
        Tomcat tomcat = new Tomcat();

        // Define port number for the web application
        String webPort = System.getenv("PORT");
        if (webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }
        // Bind the port to Tomcat server
        tomcat.setPort(Integer.valueOf(webPort));

        // Define a web application context.
        Context context = tomcat.addWebapp("/tomcatembedded", new File(
                webappDirLocation).getAbsolutePath());

       // Add servlet that will register Jersey REST resources
        Tomcat.addServlet(context, "jersey-container-servlet", resourceConfig());
        context.addServletMapping("/rest/*", "jersey-container-servlet");

        tomcat.start();
        tomcat.getServer().await();
    }

    private ServletContainer resourceConfig() {
        return new ServletContainer(new ResourceConfig(
                new ResourceLoader().getClasses()));
    }

 
}

 

Test the REST Resource

Use a browser to test out the REST resource using this url

http://localhost:8080/tomcatembedded/rest/helloworld

 

That is it for now.

4 Comments

  1. nrkkalyan November 8, 2014 Reply
  2. Jimis March 9, 2016 Reply
  3. Kamesh August 4, 2016 Reply
  4. satish rotella January 12, 2017 Reply

Add a Comment

Your email address will not be published. Required fields are marked *