Friday, September 09, 2011

Embedding Tomcat 7

The following code shows how easy it is to embed Apache Tomcat 7 using the API provided by org.wso2.carbon.tomcat.BetterTomcat. BetterTomcat is a class which wraps an org.apache.catalina.startup.Tomcat object & provides a simpler API for some common scenarios. This class provides a simple API which enables you to embed & start Tomcat by writing just a few lines of code as shown below.

public void startServer() throws ServletException, LifecycleException { 
    BetterTomcat tomcat = new BetterTomcat(8080); 
    tomcat.addWebapp("/hello", WEBAPP_PATH); 
The following code shows how to start an embedded Tomcat server with one HTTP connector on port 8080 & one HTTPS connector on port 8443.
public void startMultipleConnectors() throws LifecycleException, ServletException { 
    BetterTomcat tomcat = new BetterTomcat(); 
    tomcat.addConnector(BetterTomcat.Protocol.HTTP_11_NIO, 8080); 
    Connector https = tomcat.addConnector(BetterTomcat.Protocol.HTTPS_11_NIO, 8443); 
    https.setProperty("keystoreFile", KEYSTORE_PATH); 
    https.setProperty("keystorePass", "wso2carbon"); 
    tomcat.addWebapp("/hello", WEBAPP_PATH); 

The BetterTomcat class is used for starting up embedded Tomcat 7, which forms the core of WSO2 Carbon, WSO2 AS, WSO2 Stratos & StratosLive. If you are interested in checking out the code, have a look at the following links.

The org.wso2.carbon.tomcat OSGi bundle (#2 above) is a self contained jar file which contains all the dependencies needed to run embedded Tomcat.

Please note that this is not distributed as a separate product, but only a class in the WSO2 Carbon core libraries, and is  only used internally.

Tomcat is a trademark of the Apache Software Foundation.

Post a Comment