Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

java - Deploy WAR in embedded Tomcat 7

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...