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

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

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

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

那么,是否可以使用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(); 

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

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

从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(); 

我正在使用以下方法:

 private static final String TOMCAT = "D:/test_tomcat"; @BeforeClass public static void runTomcat() { bootstrap = new Bootstrap(); bootstrap.setCatalinaHome(TOMCAT); try { bootstrap.start(); } catch (Exception e) { e.printStackTrace(); fail("Не удалось запустить Tomcat"); } } @AfterClass public static void stopTomcat() { try { bootstrap.stop(); } catch (Exception e) { e.printStackTrace(); } } 

但方法有一个问题 – 每次更改源代码时我都需要在’webapps’目录中复制WAR文件。 我喜欢从web-inf中的classpath复制我的类,并从web-inf / lib中的classpath复制’jar’。

是的。 但是我很无聊,你的考试需要多长时间。 您必须修复测试以不依赖于服务器启动和关闭。 它可以很好地在容器内运行测试,但容器应该在测试之前启动一次。

那么回答你的问题,你可以使用系统调用从Java执行相关的.sh.bat文件。 像下面的东西,

 Runtime r = Runtime.getRuntime(); Process p = r.exec("start.sh"); p.waitFor();