如何嵌入Tomcat 6?

时间:2009-03-12 19:00:23

标签: java tomcat tomcat6

我目前正在生产Tomcat 6上运行我的webapps,并希望评估在嵌入模式下运行Tomcat。

除了api documentation中的内容之外,是否有一个好的教程或其他资源?

6 个答案:

答案 0 :(得分:40)

代码不言而喻。请参阅pom.xml片段和运行tomcat的类。

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>catalina</artifactId>
        <version>6.0.18</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>coyote</artifactId>
        <version>6.0.18</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>jasper</artifactId>
        <version>6.0.18</version>
        <scope>test</scope>
    </dependency>


public class RunWebApplicationTomcat {

    private String path = null;
    private Embedded container = null;
    private Log logger = LogFactory.getLog(getClass());

    /**
     * The directory to create the Tomcat server configuration under.
     */
    private String catalinaHome = "tomcat";

    /**
     * The port to run the Tomcat server on.
     */
    private int port = 8089;

    /**
     * The classes directory for the web application being run.
     */
    private String classesDir = "target/classes";

    /**
     * The web resources directory for the web application being run.
     */
    private String webappDir = "mywebapp";

    /**
     * Creates a single-webapp configuration to be run in Tomcat on port 8089. If module name does
     * not conform to the 'contextname-webapp' convention, use the two-args constructor.
     * 
     * @param contextName without leading slash, for example, "mywebapp"
     * @throws IOException
     */
    public RunWebApplicationTomcat(String contextName) {
        Assert.isTrue(!contextName.startsWith("/"));
        path = "/" + contextName;
    }

    /**
     * Starts the embedded Tomcat server.
     * 
     * @throws LifecycleException
     * @throws MalformedURLException if the server could not be configured
     * @throws LifecycleException if the server could not be started
     * @throws MalformedURLException
     */
    public void run(int port) throws LifecycleException, MalformedURLException {
        this.port = port;
        // create server
        container = new Embedded();
        container.setCatalinaHome(catalinaHome);
        container.setRealm(new MemoryRealm());

        // create webapp loader
        WebappLoader loader = new WebappLoader(this.getClass().getClassLoader());

        if (classesDir != null) {
            loader.addRepository(new File(classesDir).toURI().toURL().toString());
        }

        // create context
        // TODO: Context rootContext = container.createContext(path, webappDir);
        Context rootContext = container.createContext(path, webappDir);
        rootContext.setLoader(loader);
        rootContext.setReloadable(true);

        // create host
        // String appBase = new File(catalinaHome, "webapps").getAbsolutePath();
        Host localHost = container.createHost("localHost", new File("target").getAbsolutePath());
        localHost.addChild(rootContext);

        // create engine
        Engine engine = container.createEngine();
        engine.setName("localEngine");
        engine.addChild(localHost);
        engine.setDefaultHost(localHost.getName());
        container.addEngine(engine);

        // create http connector
        Connector httpConnector = container.createConnector((InetAddress) null, port, false);
        container.addConnector(httpConnector);

        container.setAwait(true);

        // start server
        container.start();

        // add shutdown hook to stop server
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                stopContainer();
            }
        });
    }
    /**
     * Stops the embedded Tomcat server.
     */
    public void stopContainer() {
        try {
            if (container != null) {
                container.stop();
            }
        } catch (LifecycleException exception) {
            logger.warn("Cannot Stop Tomcat" + exception.getMessage());
        }
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public static void main(String[] args) throws Exception {
        RunWebApplicationTomcat inst = new RunWebApplicationTomcat("mywebapp");
        inst.run(8089);
    }

    public int getPort() {
        return port;
    }

}

答案 1 :(得分:16)

虽然这篇文章有些陈旧,但我回答了自己的答案,因为它可以节省其他一些&#39;时间

package com.creativefella;

import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Embedded;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TomcatServer {
    private Embedded server;
    private int port;
    private boolean isRunning;

    private static final Logger LOG = LoggerFactory.getLogger(TomcatServer.class);
    private static final boolean isInfo = LOG.isInfoEnabled();


/**
 * Create a new Tomcat embedded server instance. Setup looks like:
 * <pre><Server>
 *    <Service>
 *        <Connector />
 *        <Engine&gt
 *            <Host>
 *                <Context />
 *            </Host>
 *        </Engine>
 *    </Service>
 *</Server></pre>
 * <Server> & <Service> will be created automcatically. We need to hook the remaining to an {@link Embedded} instnace
 * @param contextPath Context path for the application
 * @param port Port number to be used for the embedded Tomcat server
 * @param appBase Path to the Application files (for Maven based web apps, in general: <code>/src/main/</code>)
 * @param shutdownHook If true, registers a server' shutdown hook with JVM. This is useful to shutdown the server
 *                      in erroneous cases.
 * @throws Exception
 */
    public TomcatServer(String contextPath, int port, String appBase, boolean shutdownHook) {
        if(contextPath == null || appBase == null || appBase.length() == 0) {
            throw new IllegalArgumentException("Context path or appbase should not be null");
        }
        if(!contextPath.startsWith("/")) {
            contextPath = "/" + contextPath;
        }

        this.port = port;

        server  = new Embedded();
        server.setName("TomcatEmbeddedServer");

        Host localHost = server.createHost("localhost", appBase);
        localHost.setAutoDeploy(false);

        StandardContext rootContext = (StandardContext) server.createContext(contextPath, "webapp");
        rootContext.setDefaultWebXml("web.xml");
        localHost.addChild(rootContext);

        Engine engine = server.createEngine();
        engine.setDefaultHost(localHost.getName());
        engine.setName("TomcatEngine");
        engine.addChild(localHost);

        server.addEngine(engine);

        Connector connector = server.createConnector(localHost.getName(), port, false);
        server.addConnector(connector);

        // register shutdown hook
        if(shutdownHook) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    if(isRunning) {
                        if(isInfo) LOG.info("Stopping the Tomcat server, through shutdown hook");
                        try {
                            if (server != null) {
                                server.stop();
                            }
                        } catch (LifecycleException e) {
                            LOG.error("Error while stopping the Tomcat server, through shutdown hook", e);
                        }
                    }
                }
            });
        }

    }

    /**
     * Start the tomcat embedded server
     */
    public void start() throws LifecycleException {
        if(isRunning) {
            LOG.warn("Tomcat server is already running @ port={}; ignoring the start", port);
            return;
        }

        if(isInfo) LOG.info("Starting the Tomcat server @ port={}", port);

        server.setAwait(true);
        server.start();
        isRunning = true;
    }

    /**
     * Stop the tomcat embedded server
     */
    public void stop() throws LifecycleException {
        if(!isRunning) {
            LOG.warn("Tomcat server is not running @ port={}", port);
            return;
        }

        if(isInfo) LOG.info("Stopping the Tomcat server");

        server.stop();
        isRunning = false;
    }

    public boolean isRunning() {
        return isRunning;
    }

}

我还遇到了 404 错误并且花了一些时间。通过查看日志&#39; INFO: No default web.xml&#39;,我怀疑(如果这是一个警告,很容易发现)。诀窍是使用Tomcat web.xml提供的rootContext.setDefaultWebXml("web.xml") conf/web.xml。原因是,它包括DefaultServlet,它提供像HTML,JS这样的静态文件。使用web.xml或在代码中手动注册servlet。

<强>用法

// start the server at http://localhost:8080/myapp
TomcatServer server = new TomcatServer("myapp", 8080, "/src/main/", true);
server.start();
// .....
server.stop();

不要忘记将默认web.xml放在此程序的同一目录中,或指向正确的位置。

应该注意的是,关闭钩子的灵感来自Antonio's answer

答案 2 :(得分:11)

为什么人们可以在Jetty上使用Tomcat有很多原因:

  1. 一个人已熟悉Tomcat
  2. 一个是开发需要轻松传输到Tomcat安装的Web应用程序
  3. Jetty开发者文档实际上比Tomcat更令人惊讶(太棒了!)
  4. 在Jetty社区中回答问题有时可能需要数年时间,如2007年所示。请参阅Embedding Jetty
  5. 重要事项:在Jetty 6.1。*之后,每个Web应用程序都会打开自己的JVM,因此如果您尝试在独立访问和Web应用程序之间获得编程访问权限,那么您唯一的希望就是通过Web API。
  6. 如果这对您来说是一个问题,Tomcat是一个开源项目,其知识产权归Apache Foundation所有,Jetty是开源的,但由一家小型私人公司(Mortbay Consulting)拥有
  7. 第5点在我的工作中非常重要。例如,我可以通过Tomcat直接访问JSPWiki实例,但是在使用Jetty时它是完全无法访问的。我在2007年要求解决这个问题,但还没有听到答案。所以我终于放弃并开始使用Tomcat 6.我已经研究过Glassfish和Grizzly,但到目前为止,Tomcat(令人惊讶地)是最稳定且记录良好的Web容器(实际上并没有多说)。

答案 3 :(得分:2)

这可能会有所帮助。

如果你下载了Tomcat6.x的源代码包,你会得到这个类:

http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/startup/Catalina.html#main(java.lang.String[])

这是一个如何使用Embedd类的示例:它是一个用于停止|启动特定Tomcat安装的shell。 (我的意思是你可以设置CATALINA_BASE指向现有的Tomcat安装。)

如果你编译它,你可以这样运行:

java -D“catalina.base =%CATALINA_BASE%” - D“catalina.home =%CATALINA_HOME%”org.apache.catalina.startup.Catalina start

我不知道如何更改此代码以关闭服务器!

答案 4 :(得分:0)

几个月前读完这个帖子后,我写了这个项目:spring-embedded-tomcat。 它可以用于将tomcat6嵌入到基于Spring的应用程序中。

答案 5 :(得分:0)

我认为使用Tomcat 7或Jetty 9嵌入更容易。在这里你会找到一个很好的介绍:http://www.hascode.com/2013/07/embedding-jetty-or-tomcat-in-your-java-application/