Embedding Tomcat Into Java Applications



Using Tomcat

Embedding Tomcat Into Java Applications

In this article, we'll extend our Tomcat discussions to the application level by creating a Java application that manages an embedded version of the Tomcat JSP/servlet container. Tomcat can be broken down into a set of containers, each with their own purpose. These containers are by default configured using the server.xml file. When embedding, you will not be using this file; therefore, you will need to assemble instances of these containers programmatically. The following XML code snippet contains the hierarchy of the Tomcat containers:


<Server>
  <Service>
    <Connector />
    <Engine>
      <Host>
        <Context />
      </Host>
    </Engine>
  </Service>
</Server>

Note: Each of the previously listed elements contains attributes to set their appropriate behaviors, but for our purposes, only the element hierarchies and relationships are important.


This is the structure that we need to create with our embedded application. The <Server> and <Service> elements of this structure are going to be implicitly created, therefore we do not have to create these objects ourselves. The steps to create the remainder of the container structure are listed below.

These are the same steps that we must perform in order to create our own embedded version of the Tomcat container:

  1. Create an instance of an org.apache.catalina.Engine; this object represents the <Engine> element above 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 theEngine object.
  3. Now you need to create n-number of org.apache.catalina.Context objects that will represent each Web application in this Host.
  4. Once each of your Contexts are created, you then need to add each of the created Contexts to the previously created Host. For our example, we'll create a single Context that will represent our onjava application.
  5. The final step is to create an org.apache.catalina.Connector object and associate it with the previously created Engine. The Connector object is the object that actually receives a request from the calling client.

To create this application, we'll leverage some existing Tomcat classes that have been developed to ease this type of integration. The main class we will use is the org.apache.catalina.startup.Embedded class, which can be found in the <CATALINA_HOME>/src/catalina/src/share/org/apache/catalina/startup directory. The following source listing contains our sample application that builds these containers using theorg.apache.catalina.startup.Embedded class.

package onjava;

import java.net.URL;
import org.apache.catalina.Connector;
import org.apache.catalina.Context;
import org.apache.catalina.Deployer;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.logger.SystemOutLogger;
import org.apache.catalina.startup.Embedded;
import org.apache.catalina.Container;

public class EmbeddedTomcat {

  private String path = null;
  private Embedded embedded = null;
  private Host host = null;
  /**
    * Default Constructor
    *
    */
  public EmbeddedTomcat() {

  }

  /**
    * Basic Accessor setting the value of the context path
    *
    * @param path - the path
    */
  public void setPath(String path) {

    this.path = path;
  }

  /**
    * Basic Accessor returning the value of the context path
    *
    * @return - the context path
    */
  public String getPath() {

    return path;
  }

  /**
    * This method Starts the Tomcat server.
    */
  public void startTomcat() throws Exception {

    Engine engine = null;
    // Set the home directory
    System.setProperty("catalina.home", getPath());

    // Create an embedded server
    embedded = new Embedded();
    // print all log statments to standard error
    embedded.setDebug(0);
    embedded.setLogger(new SystemOutLogger());

    // Create an engine
    engine = embedded.createEngine();
    engine.setDefaultHost("localhost");

    // Create a default virtual host
    host = embedded.createHost("localhost", getPath()
      + "/webapps");
    engine.addChild(host);

    // Create the ROOT context
    Context context = embedded.createContext("",
      getPath() + "/webapps/ROOT");
    host.addChild(context);

    // Install the assembled container hierarchy
    embedded.addEngine(engine);

    // Assemble and install a default HTTP connector
    Connector connector =
      embedded.createConnector(null, 8080, false);
    embedded.addConnector(connector);
    // Start the embedded server
    embedded.start();
  }

  /**
    * This method Stops the Tomcat server.
    */
  public void stopTomcat() throws Exception {
    // Stop the embedded server
    embedded.stop();
  }

  /**
    * Registers a WAR with the container.
    *
    * @param contextPath - the context path under which the
    *               application will be registered
    * @param warFile - the URL of the WAR to be
    * registered.
    */
  public void registerWAR(String contextPath, URL warFile)
    throws Exception {

    if ( contextPath == null ) {

      throw new Exception("Invalid Path : " + contextPath);
    }
    if( contextPath.equals("/") ) {

      contextPath = "";
    }
    if ( warFile == null ) {

      throw new Exception("Invalid WAR : " + warFile);
    }

    Deployer deployer = (Deployer)host;
    Context context = deployer.findDeployedApp(contextPath);

    if (context != null) {

      throw new
        Exception("Context " + contextPath
        + " Already Exists!");
    }
    deployer.install(contextPath, warFile);
  }

  /**
    * Unregisters a WAR from the web server.
    *
    * @param contextPath - the context path to be removed
    */
  public void unregisterWAR(String contextPath)
    throws   Exception {

    Context context = host.map(contextPath);
    if ( context != null ) {

      embedded.removeContext(context);
    }
    else {

      throw new
        Exception("Context does not exist for named path : 
        + contextPath);
    }
  }

  public static void main(String args[]) {

    try {

      EmbeddedTomcat tomcat = new EmbeddedTomcat();
      tomcat.setPath("d:/jakarta-tomcat-4.0.1");
      tomcat.startTomcat();

      URL url =
        new URL("file:D:/jakarta-tomcat-4.0.1"
        + "/webapps/onjava");
      tomcat.registerWAR("/onjava", url);

      Thread.sleep(1000000);

      tomcat.stopTomcat();

      System.exit(0);
    }
    catch( Exception e ) {

      e.printStackTrace();
    }
  }
}

You should begin your examination of the EmbeddedTomcat application source with the main() method. This method first creates an instance of the EmbeddedTomcatclass. It then sets the path of the Tomcat installation that will be hosting our Tomcat instance. This path is equivalent to the <CATALINA_HOME> environment variable. The next action performed by the main() method is to invoke thestartTomcat() method. This is the method that implements the container-construction steps described earlier. The steps performed by this method are listed below.



  1. The main() method begins by setting the system property to the value of the path attribute:

      // Set the home directory
      System.setProperty("catalina.home", getPath());

    Note:

    Make sure you use the value of <CATALINA_HOME> as the directory value passed to the setPath()method.


  2. The next step performed by this method is to create an instance of the Embedded object and set the debug level and current logger.

      // Create an embedded server
      embedded = new Embedded();
      embedded.setDebug(5);
      // print all log statments to standard error
      embedded.setLogger(new SystemOutLogger());

    Note:

    The debug level should be 0, when deploying a production Web application. Setting the debug level to 0 reduces the amount of logging performed by Tomcat, which will improve performance significantly.


  3. After the application has an instance of the Embedded object, it creates an instance of anorg.apache.catalina.Engine and sets the name of the default host. The Engine object represents the entire Catalina servlet container.

      // Create an engine
      engine = embedded.createEngine();
      engine.setDefaultHost("localhost");
  4. After an Engine has been instantiated, we create an org.apache.catalina.Host object, named localhost, with a path pointing to the <CATALINA_HOME>/webapps/ directory, and add it the Engine object. The Host object defines the virtual hosts that are contained in each instance of a Catalina Engine.

      // Create a default virtual host
      host = embedded.createHost("localhost", getPath() +
        "/webapps");
    
      engine.addChild(host);
  5. The next step performed by the startTomcat() method is to create an org.apache.catalina.Context object, which represents the ROOT Web application packaged with Tomcat, and add it the to the previously created Host. The ROOT Web application is the only application that will be installed by default.

      // Create the ROOT context
      Context context = embedded.createContext("",
        getPath() + "/webapps/ROOT");
        host.addChild(context);
  6. The next step adds the Engine containing the created Host and Context to the Embedded object.

      // Install the assembled container hierarchy
      embedded.addEngine(engine);
  7. After the engine is added to the Embedded object, the startTomcat() method creates anorg.apache.catalina.Connector object and associates it with the previously created Engine. The<Connector> element defines the class that does the actual handling of requests and responses to and from a calling client application. In the following snippet, an HTTP connector that listens to port 8080 is created and added to the Embedded object.

      // Assemble and install a default HTTP connector
      Connector connector = embedded.createConnector(null,
        8080, false);
      embedded.addConnector(connector);
  8. The final step performed by the startTomcat() method starts the Tomcat container.

      embedded.start();

When startTomcat() returns, the main method calls the registerWAR() method, which installs the previously deployed onjava application to the Embedded object. The URL used in this example can point to any Webapp directory that follows the specification for Java Servlet 2.2 and later.

  URL url =
    new URL("file:D:/jakarta-tomcat-4.0.1"
    + "/webapps/onjava");
  tomcat.registerWAR("/onjava", url);

The main application is then put to sleep to allow the embedded server time to service requests. When the application awakes, the embedded server is stopped and the application exits.

To test this application, you must complete the following steps:

  1. Compile the EmbeddedTomcat.java class.
  2. Make sure all other instances of Tomcat are shut down.
  3. Add the following jar files, all of which can be found in the Tomcat installation, to your application classpath.
    • <CATALINA_HOME>/bin/bootstrap.jar
    • <CATALINA_HOME>/server/lib/catalina.jar
    • <CATALINA_HOME>/server/lib/servlet-cgi.jar
    • <CATALINA_HOME>/server/lib/servlets-common.jar
    • <CATALINA_HOME>/server/lib/servlets-default.jar
    • <CATALINA_HOME>/server/lib/servlets-invoker.jar
    • <CATALINA_HOME>/server/lib/servlets-manager.jar
    • <CATALINA_HOME>/server/lib/servlets-snoop.jar
    • <CATALINA_HOME>/server/lib/servlets-ssi.jar
    • <CATALINA_HOME>/server/lib/servlets-webdav.jar
    • <CATALINA_HOME>/server/lib/jakarta-regexp-1.2.jar
    • <CATALINA_HOME>/lib/naming-factory.jar
    • <CATALINA_HOME>/common/lib/crimson.jar
    • <CATALINA_HOME>/common/lib/jasper-compiler.jar
    • <CATALINA_HOME>/common/lib/jasper-runtime.jar
    • <CATALINA_HOME>/common/lib/jaxp.jar
    • <CATALINA_HOME>/common/lib/jndi.jar
    • <CATALINA_HOME>/common/lib/naming-common.jar
    • <CATALINA_HOME>/common/lib/naming-resources.jar
    • <CATALINA_HOME>/common/lib/servlet.jar
    • <CATALINA_HOME>/common/lib/tools.jar
  4. Make sure that your classpath includes the directory containing the compiled EmbeddedTomcat class.
  5. Execute the following command:
      java onjava.EmbeddedTomcat

If everything went according to plan, you should see some log statements in the console window:

  HttpProcessor[8080][0] Starting background thread
  HttpProcessor[8080][0]  Background thread has been started
  HttpProcessor[8080][1] Starting background thread
  HttpProcessor[8080][1]  Background thread has been started
  HttpProcessor[8080][2] Starting background thread
  HttpProcessor[8080][2]  Background thread has been started
  HttpProcessor[8080][3] Starting background thread
  HttpProcessor[8080][3]  Background thread has been started
  HttpProcessor[8080][4] Starting background thread
  HttpProcessor[8080][4]  Background thread has been started

Once you see the previous text, you will be able to access the ROOT and /onjava Web applications using the following URLs:

  • http://localhost:8080/
  • http://localhost:8080/onjava/

Note: The onjava application that we are using throughout this article is the Web application from my previous Tomcat articles.





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
东南亚位于我国倡导推进的“一带一路”海陆交汇地带,作为当今全球发展最为迅速的地区之一,近年来区域内生产总值实现了显著且稳定的增长。根据东盟主要经济体公布的最新数据,印度尼西亚2023年国内生产总值(GDP)增长5.05%;越南2023年经济增长5.05%;马来西亚2023年经济增速为3.7%;泰国2023年经济增长1.9%;新加坡2023年经济增长1.1%;柬埔寨2023年经济增速预计为5.6%。 东盟国家在“一带一路”沿线国家中的总体GDP经济规模、贸易总额与国外直接投资均为最大,因此有着举足轻重的地位和作用。当前,东盟与中国已互相成为双方最大的交易伙伴。中国-东盟贸易总额已从2013年的443亿元增长至 2023年合计超逾6.4万亿元,占中国外贸总值的15.4%。在过去20余年中,东盟国家不断在全球多变的格局里面临挑战并寻求机遇。2023东盟国家主要经济体受到国内消费、国外投资、货币政策、旅游业复苏、和大宗商品出口价企稳等方面的提振,经济显现出稳步增长态势和强韧性的潜能。 本调研报告旨在深度挖掘东南亚市场的增长潜力与发展机会,分析东南亚市场竞争态势、销售模式、客户偏好、整体市场营商环境,为国内企业出海开展业务提供客观参考意见。 本文核心内容: 市场空间:全球行业市场空间、东南亚市场发展空间。 竞争态势:全球份额,东南亚市场企业份额。 销售模式:东南亚市场销售模式、本地代理商 客户情况:东南亚本地客户及偏好分析 营商环境:东南亚营商环境分析 本文纳入的企业包括国外及印尼本土企业,以及相关上下游企业等,部分名单 QYResearch是全球知名的大型咨询公司,行业涵盖各高科技行业产业链细分市场,横跨如半导体产业链(半导体设备及零部件、半导体材料、集成电路、制造、封测、分立器件、传感器、光电器件)、光伏产业链(设备、硅料/硅片、电池片、组件、辅料支架、逆变器、电站终端)、新能源汽车产业链(动力电池及材料、电驱电控、汽车半导体/电子、整车、充电桩)、通信产业链(通信系统设备、终端设备、电子元器件、射频前端、光模块、4G/5G/6G、宽带、IoT、数字经济、AI)、先进材料产业链(金属材料、高分子材料、陶瓷材料、纳米材料等)、机械制造产业链(数控机床、工程机械、电气机械、3C自动化、工业机器人、激光、工控、无人机)、食品药品、医疗器械、农业等。邮箱:market@qyresearch.com

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值