如何使用 Java 启动和停止 Tomcat 容器? [英] How to start and stop an Tomcat container with Java?

查看:32
本文介绍了如何使用 Java 启动和停止 Tomcat 容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Maven 项目,它为预集成测试(jUnit 测试)启动一个 tomcat 容器.我的大多数测试都需要重新启动被测 Web 应用程序.所以我想在执行每个 jUnit 测试之前重新启动 Tomcat 容器.

I have a Maven project that starts a tomcat container for pre-integration-tests (jUnit Tests). Most of my tests require that the web-application under tests is restarted. So I'd like to restart the Tomcat container before each jUnit test is executed.

至于现在我使用cargo-maven2-plugin来配置tomcat容器.

As for now I use the cargo-maven2-plugin to configure the tomcat container.

那么,是否可以用java语句启动和停止容器?

So, is it possible to start and stop the container with a java statement?

推荐答案

那么,是否可以用java语句启动和停止容器?

So, is it possible to start and stop the container with a java statement?

您的用例看起来非常奇怪(必须在测试之间重新启动容器),但我们不讨论这个.要回答您的问题,是的,这是可能的,这可以使用 Cargo 的 Java API 来完成.

Your use case looks extremely weird (having to restart the container between tests) but let's not discuss this. To answer your question, yes it is possible and this can be done using Cargo's Java API.

要启动 Tomcat 容器并部署您的战争,您可以在 setUp() 方法中执行以下操作:

To start a Tomcat container and deploy your war, you can do something like this in the setUp() method:

// (1) Optional step to install the container from a URL pointing to its distribution
Installer installer = new ZipURLInstaller(new URL("http://www.apache.org/dist/tomcat/tomcat-6/v6.0.20/bin/apache-tomcat-6.0.20.zip"));
installer.install();

// (2) Create the Cargo Container instance wrapping our physical container
LocalConfiguration configuration = (LocalConfiguration) new DefaultConfigurationFactory()
        .createConfiguration("tomcat6x"), ContainerType.INSTALLED, ConfigurationType.STANDALONE);
container = (InstalledLocalContainer) new DefaultContainerFactory()
        .createContainer("tomcat6x", ContainerType.INSTALLED, configuration);
container.setHome(installer.getHome());

// (3) Statically deploy some WAR (optional)
WAR deployable = new WAR("./webapp-testing-webapp/target/webapp-testing-webapp-1.0.war");
deployable.setContext("ROOT");
configuration.addDeployable(deployable);

// (4) Start the container
container.start();

并在 tearDown() 方法中停止它.

And stop it in the tearDown() method.

// (6) Stop the container
container.stop();

这篇关于如何使用 Java 启动和停止 Tomcat 容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆