如何使用Java启动和停止Tomcat容器?

Seb*_*app 11 java junit tomcat maven-2 unit-testing

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

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

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

Pas*_*ent 14

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

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

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

// (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();
Run Code Online (Sandbox Code Playgroud)

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

// (6) Stop the container
container.stop();
Run Code Online (Sandbox Code Playgroud)


Adi*_*Adi 5

从tomcat\bin到你的类路径的bootstrap.jar和commons-logging-api-1.1.1以及下面的代码片段可能会有所帮助,

Bootstrap bootstrap=new Bootstrap();
bootstrap.setCatalinaHome("D:/apache-tomcat-5.5.28");

bootstrap.start();

Thread.sleep(60000);

bootstrap.stop();
Run Code Online (Sandbox Code Playgroud)