首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何嵌入Tomcat6?

如何嵌入Tomcat6?
EN

Stack Overflow用户
提问于 2009-03-12 19:00:23
回答 6查看 38.2K关注 0票数 58

我目前正在Tomcat6上运行我的webapps,我想评估一下在嵌入式模式下运行Tomcat。

除了api documentation中的内容之外,还有没有好的教程或其他资源

EN

回答 6

Stack Overflow用户

发布于 2009-03-13 00:31:20

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

代码语言:javascript
复制
    <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;
    }

}
票数 40
EN

Stack Overflow用户

发布于 2011-09-26 20:34:03

虽然这篇文章有些陈旧,但我是在回答我自己的答案,因为它可以节省别人的时间。

代码语言:javascript
复制
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错误,并挣扎了一段时间。通过查看日志'INFO: No default web.xml',我怀疑这是一个警告(如果这是一个警告,那么很容易被发现)。诀窍是使用Tomcat (conf/web.xml).提供的web.xml ( rootContext.setDefaultWebXml("web.xml") )原因是,它包括DefaultServlet,它提供静态文件,如HTML,JS。使用web.xml或在代码中手动注册servlet。

使用

代码语言:javascript
复制
// 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

票数 16
EN

Stack Overflow用户

发布于 2009-12-14 12:01:03

使用Tomcat而不是Jetty的原因有很多:

Tomcat已经很熟悉Tomcat正在开发的installation

  • The应用程序需要轻松移植到Tomcat开发人员文档实际上比Tomcat社区中回答的(amazing!)

  • Getting问题还参差不齐,就像2007年一样。在Jetty6.1.*之后请参阅Embedding Jetty

  • Important:,每个web应用程序都会打开到自己的JVM中,所以如果您试图在独立访问和web应用程序之间进行编程访问,那么您唯一的希望就是通过web API。

  • 是一个开源项目,知识产权归阿帕奇基金会所有,

是开源项目,但归一家小型私人公司所有(Mortbay Consulting)

第五点在我的工作中一直很重要。例如,我可以通过Tomcat直接访问JSPWiki实例,但在使用Jetty时完全无法访问。我在2007年问过这个问题的解决方案,但还没有得到答复。所以我最终放弃了,开始使用Tomcat6。我研究了Glassfish和Grizzly,但到目前为止,Tomcat是(令人惊讶的)最稳定和文档最完善的web容器(这并不是很有说服力)。

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/640022

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档