Deploy WAR in the integrated Tomcat 7

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

My problem is how to deploy my WAR file in the embedded Tomcat?

As you may have noticed, I cannot use the tomcat maven plugin, since I want it to run with automatic tests.

+6
source share
1 answer

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 now have two options. Automatic deployment of any web application to 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 located anywhere on the hard drive.

 // 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()); 
+5
source

Source: https://habr.com/ru/post/950077/


All Articles