您的位置:首页 > 运维架构 > Tomcat

嵌入式Tomcat的实现

2008-09-18 23:08 120 查看
导读:
  import java.io.File;
  import java.net.InetAddress;
  import org.apache.catalina.Context;
  import org.apache.catalina.Engine;
  import org.apache.catalina.Host;
  import org.apache.catalina.startup.Embedded;
  public class EmbeddedTomcat {
  private String contextPath = null;
  private String hostName=null;
  private String catalinaHomePath=null;
  private int port=8080;
  private Embedded embedded = null;
  private Host host = null;
  public EmbeddedTomcat(String contextPath,String catalinaHomePath,String hostName,int port)
  {
  this.contextPath=contextPath;
  this.catalinaHomePath=catalinaHomePath;
  this.hostName=hostName;
  this.port=port;
  }
  /**
  * This method Starts the Tomcat server.
  */
  public void startTomcat() throws Exception {
  // Create an embedded server
  embedded = new Embedded();
  Engine engine = null;
  // System.setProperty("catalina.home", getPath());
  embedded.setCatalinaHome(catalinaHomePath);
  // Create an engine
  engine = embedded.createEngine();
  // Create a default virtual host
  host = embedded.createHost(hostName, contextPath+"/webapps");
engine.setDefaultHost(host.getName());
        // Create the ROOT context

        Context rootCxt = embedded.createContext("",contextPath + "/webapps/ROOT");

        Context manageCxt = embedded.createContext("/manager",contextPath+"/webapps/manager");

        //Create your own context

        Context scoreCxt = embedded.createContext("/vmm", contextPath+"/webapps/vmm");

        rootCxt.setPrivileged(true);

        host.addChild(rootCxt);

        host.addChild(manageCxt);

        host.addChild(scoreCxt);

        // Install the assembled container hierarchy

        embedded.addEngine(engine);

        // Assemble and install a default HTTP connector

        embedded.addConnector(embedded.createConnector(InetAddress.getByName(null), port, false));

        // Start the embedded server

        embedded.start();

      }

      /**

        * This method Stops the Tomcat server.

        */

      public void stopTomcat() throws Exception {

        // Stop the embedded server

        embedded.stop();

      }

      public static void main(String args[]) {

        try {

          String contextPath=(new File(".")).getCanonicalPath();

          String catalinaHomePath =(new File("./conf/tomcat")).getCanonicalPath();

          String hostName="localhost";

          int port =80;

          System.out.println("contextPath:"+contextPath);

          System.out.println("catalinaHomePath:"+catalinaHomePath);

          EmbeddedTomcat tomcat = new EmbeddedTomcat(contextPath,catalinaHomePath,hostName,port);

          tomcat.startTomcat();

        }

        catch( Exception e ) {

          e.printStackTrace();

        }

      }

    }

本文转自
http://java.chinaitlab.com/Tomcat/755514.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: