A ready-to-try (and build) example of Apache Tomcat 7 server embedding in a Java application, using the new (as of Tomcat 7) tomcat-embed*.jar server implementation. Embedding is much easier than it used to be and can be done in a fully programmatic way (without having to supply server.xml, web.xml etc.). This example is based on Mark Thomas' slides (see link below) and includes the very basic server configuration and two servlets.

  • To run the example: java -jar dist/embed1.jar
  • To rebuild: ant clean dist
  • To test: http://localhost:9090/

Download: tc7emb.zip - 4609435 bytes

The example includes the required Tomcat libraries, you can also download the latest version of these from http://tomcat.apache.org/download-70.cgi (look for "embedded"). There is also a NetBeans project (in the netbeans subdirectory) for ease of browsing/editing, note that the build.xml file is fully stand-alone and does not depend on any extra tools other than the JDK.
Snippet:
                // This is the minimal tomcat instance we need for embedding
                Tomcat tomcat = new Tomcat();
                // set http listen port for the default connector we get out-of-the-box
                // (there's a lot more you can customize, see the javadoc)
                tomcat.setPort(9090);
                // set up context,
                //  "" indicates the path of the ROOT context
                //  tmpdir is used as docbase because we are not serving any files in this example
                File base = new File(System.getProperty("java.io.tmpdir"));
                Context rootCtx = tomcat.addContext("", base.getAbsolutePath());
                // Add the 'killer switch' servlet (used to shut down the server) to the context
                Tomcat.addServlet(rootCtx, "KillerSwitch", new KillerSwitch());
                rootCtx.addServletMapping("/shutdown", "KillerSwitch");
                // Add the main page servlet to the context
                Tomcat.addServlet(rootCtx, "Servlet1", new Servlet1());
                rootCtx.addServletMapping("/*", "Servlet1");
                // ..and we are good to go
                tomcat.start();
For more on Tomcat 7 embedding see: this presentation, the official javadocs and of course Google tomcat 7 embedded.