Deploy WAR in embedded Tomcat 7

会有一股神秘感。 提交于 2019-12-29 06:13:54

问题


I currently need to create a server in order to run a number of unit test. To simplify this process I would like to embed Tomcat into my code and load an instance of Tomcat (which in turn loads my WAR file) before running the unit test (using the @BeforeClass notation).

My issue is how can I deploy my WAR file into the embedded Tomcat?

As you might notice I cannot use the tomcat maven plugin since I want it to run with the automated tests.


回答1:


This code works with Tomcat 8.0:

File catalinaHome = new File("..."); // folder must exist
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080); // HTTP port
tomcat.setBaseDir(catalinaHome.getAbsolutePath());
tomcat.getServer().addLifecycleListener(new VersionLoggerListener()); // nice to have

You have now two options. Automatically deploy any web app in catalinaHome/webapps:

// This magic line makes Tomcat look for WAR files in catalinaHome/webapps
// and automatically deploy them
tomcat.getHost().addLifecycleListener(new HostConfig());

Or you can manually add WAR archives. Note: They can be anywhere on the hard disk.

// Manually add WAR archives to deploy.
// This allows to define the order in which the apps are discovered
// plus the context path.
File war = new File(...);
tomcat.addWebapp("/contextPath", war.getAbsolutePath());


来源:https://stackoverflow.com/questions/17809914/deploy-war-in-embedded-tomcat-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!