Embedding Tomcat services

Embedding Tomcat server

To create a Java application that contains an embedded version of the Tomcat server, we will leverage some existing Tomcat classes that have been developed to ease this type of integration.

The main class we want to use is org.apache.catalina.startup.Embedded, which can be found in the <CATALINA_HOME>/src/catalina/src/share/org/apache/catalina/startup directory.

You can open this file and skim over it. (You don't need to examine it in too much detail). We will look at certain parts of the Embedded object as we leverage it to build our own application.

Recall from Chapter 1 that Tomcat can be subdivided into a set of containers with each having their own purpose. These containers are by default configured using the server.xml file.

When embedding a version of Tomcat, you won't have this file available, and so you need to assemble instances of these containers programmatically. The following XML code snippet, from the server.xml file, contains the hierarchy of the Tomcat containers:

<Server port="8005" shutdown="SHUTDOWN" debug="0"> <Service name="Tomcat-Standalone"> <Connector className="org.apache.catalina.connector.http.HttpConnector" port="8080" minProcessors="5" maxProcessors="75" enableLookups="true" redirectPort="8443" acceptCount="10" debug="0" connectionTimeout="60000"/> <Engine name="Standalone" defaultHost="localhost" debug="0"> <Host name="localhost" debug="0" appBase="webapps" unpackWARs="true"> <Context path="/examples" docBase="examples" debug="0" reloadable="true"> </Context> </Host> </Engine> </Service> </Server>

This is the structure that we need to create with our embedded application. Because the <Server> and <Service> elements of this structure are implicitly created, we don't need to create these objects ourselves.

The steps to create this container structure are as follows:

  1. Create an instance of org.apache.catalina.Engine. This object represents the previous <Engine> element and acts as a container to the <Host> element.
  2. Create an org.apache.catalina.Host object, which represents a virtual host, and add this instance to the Engine object.
  3. Now you need to create N-number of org.apache.catalina.Context objects that will represent each Web application in this Host. Add each of the created Contexts to the previously created Host.
  4. Create an org.apache.catalina.Connector object and associate it with the previously created Engine. These are the steps that we must perform to create our own application containing an embedded version of the Tomcat server.
Contact sales!