Sunday, March 6, 2011

Embedded Tomcat, The Minimal Version

Tomcat 7 has been improved a lot and along with all the features that it brings, a very nice feature is provided - the API for embedding tomcat into the application. The API was provided in earlier versions of Tomcat but it was quite cumbersome to use.

To to start the embedded version of Tomcat one may need to build the required JARs.


$> svn co https://svn.apache.org/repos/asf/tomcat/trunk tomcat
$> cd tomcat
$> ant embed-jars
$> ls -l output/embed
total 5092
-rw-r--r-- 1 anton None 56802 2011-03-06 17:09 LICENSE
-rw-r--r-- 1 anton None 1194 2011-03-06 17:09 NOTICE
-rw-r--r-- 1 anton None 1690519 2011-03-06 17:09 ecj-3.6.jar
-rw-r--r-- 1 anton None 234625 2011-03-06 17:09 tomcat-dbcp.jar
-rw-r--r-- 1 anton None 2402517 2011-03-06 17:09 tomcat-embed-core.jar
-rw-r--r-- 1 anton None 781989 2011-03-06 17:09 tomcat-embed-jasper.jar
-rw-r--r-- 1 anton None 34106 2011-03-06 17:09 tomcat-embed-logging-juli.jar


The following snippet demonstrates the embedded Tomcat usage with a deployed servlet instance.

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.Writer;

public class Main {

  public static void main(String[] args)
  throws LifecycleException, InterruptedException, ServletException {
    Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);

    Context ctx = tomcat.addContext("/", new File(".").getAbsolutePath());

    Tomcat.addServlet(ctx, "hello", new HttpServlet() {
      protected void service(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException {
        Writer w = resp.getWriter();
        w.write("Hello, World!");
        w.flush();
      }
    });
    ctx.addServletMapping("/*", "hello");

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

}

The only two JARs required are tomcat-embed-core.jar and tomcat-embed-logging-juli.jar. It means that there will be no JSP support and pooling will also be disabled. But that's enough to start a servlet and in most cases that is what you probably need.

3 comments:

Hawazen said...

Fantastic, couldn't get simpler than this. Thanks

nicolas said...

Hi Very nice feature but imagine I would like to integrate this feature into an existing project. Is it possible to have JSP support and other technologies.

I know it is possible to embed glassfis so.

Best regards,

Anton Arhipov said...

@nicolas.

Sure it is possible. Just need a couple more dependencies in the classpath: jasper and ejc