Hi,
this is a question about embedding Tomcat into an application so that
it can still be configured using server.xml and web applications can be
added or removed programmatically.
I am using Tomcat 6.0.24.
The way I tried to make it work is by instantiating an instance of
Catalina, feeding in all necessary config and then adding
StandardContext instances as needed to a named host of a named service
etc. However there is a bug (I believe) in Catalina that made me
subclass Catalina and add a getServer() method:
public class MyCatalina extends Catalina {
public Server getServer() {
return this.server;
}
}
This is due to Catalina declaring its own protected member variable
"server" and a corresponding "setServer" method, while Catalina's super
class Embedded has a private member "server" and a "getServer" method,
so that Catalina sets its "service" member, but when asking, will return
super.server which is consistently null.
With that fix, the sample code below works as expected. Still: As I
ran into the problem noted above, I was wondering whether the whole
approach makes sense or whether there is a better way of using
server.xml while embedding tomcat but without using the Catalina class.
Thanks,
Henning
Sample code:
//
//
MyCatalina c = new MyCatalina();
File cf = new File("conf/server.xml");
c.setConfig(cf.getAbsolutePath());
c.setUseShutdownHook(false);
c.setAwait(false);
c.start();
// add a web app from a folder
File wc = new File("webapp");
StandardContext sc = (StandardContext)
c.createContext("/test",wc.getAbsolutePath());
File wd = new File("work");
if (!wd.exists()) {
wd.mkdir();
}
sc.setWorkDir(wd.getAbsolutePath());
// could be made configurable!
Container ch =
c.getServer().findService("Catalina").getContainer().findChild("localhost");
ch.addChild(sc);