Blog.  Engineering at Spinneret.

Minimal Embedded Tomcat

When thinking about embedding a servlet container into a Java application, most think of Jersey. Although Tomcat has had the capability of being embedded into applications for a long time, it is normally used as an application server to host one or more applications.

Getting the JARS

You can get the required jars from the Tomcat Downloads (make sure you get the embedded versions) or, of course, by using Maven.

Very Simple Configuration

The following creates a very simple, but fully functional embedded Tomcat application:

Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
Context context = tomcat.addWebapp("", new File("web").getAbsolutePath());
tomcat.start();
tomcat.getServer().await();

The "web" directory would include your usual "WEB-INF" and "META-INF" directories and all other CSS and scripts. Your "web.xml" file should be placed inside your "WEB-INF" directory.

Note that the return value of the "addWebapp" method is set to the "context" variable. This is not required, but will be useful if the context will be used for other purposes (see below).

Adding GZIP Compression

You can easily add GZIP compression to selected file types:

Connector c = tomcat.getConnector();
c.setProperty("compression", "on");
c.setProperty("compressionMinSize", "1024");
c.setProperty("noCompressionUserAgents", "gozilla, traviata");
c.setProperty("compressableMimeType", "text/html,text/xml, text/css, application/json, " +
			"application/javascript");
Adding Tomcat Valves

You can also add a Valve Component to the StandardContext. The following code adds a Remote IP Valve, useful if your Tomcat instances sit behind a load balancer:

RemoteIpValve remoteIpValve = new RemoteIpValve();
((StandardContext) context).addValve(remoteIpValve);
Adding Naming Resources

You can add Naming Resources, for example a JDBC datasource, easily too. Here is code that creates a Data Source Context Resource:

String connectionString = "YOUR_CONNECTION_STRING";
ContextResource resource = new ContextResource();
resource.setName("jdbc/db");
resource.setAuth("Container");
resource.setType("javax.sql.DataSource");
resource.setScope("Sharable");
resource.setProperty("driverClassName", "com.mysql.jdbc.Driver");
resource.setProperty("removeAbandonedTimeout", "60");
resource.setProperty("initialSize", "10");
resource.setProperty("minIdle", "10");
resource.setProperty("maxTotal", "100");
resource.setProperty("url", connectionString);

To add this resource to Tomcat, you can use the following code:

context.getNamingResources().addResource(resource);
Can Java be this "Simple"?

As you can see, it is trivial to create an embedded Tomcat application that will surely impress your hipster Node JS friends.

Happy Coding!