Search code examples
javatomcatvirtual-hosts

Tomcat: Change the Virtual hosts programmatically?


Tomcat offers a build in "Virtual Hosting" Support: An Engine/Web-Application can be configured to be responsible for a list of Domains. These Domains have to be put into the server.xml/context.xml files with a special xml directive.

=> Is there any possibility to change the Tomcat Configuration (in general) and especially the "Virtual Hosts" of a Web-Application/Engine programmatically?

For example if a new user signs up, I have to add his domain to the list of "accepted virtual hosts/domains". The only way I currently think of is changing the xml files via a script and then restart Tomcat.

Is there any way to add them add runtime via some Java-Methods programmatically?

Thank you very much! Jan


Solution

  • Tomcat provides APIs to create new virtual host. To get access to the wrapper object needed for this, you need to implement a ContainerServlet. You can create virtual host like this,

        Context context = (Context) wrapper.getParent();
        Host currentHost = (Host) context.getParent();
        Engine engine = (Engine) currentHost.getParent();
    
        StandardHost host = new StandardHost();
        host.setAppBase(appBase);
        host.setName(domainName);
    
        engine.addChild(host);
    

    You need to make sure appBase directory exist and you have to find ways to persist the new host to the server.xml or you lose the host on restart.

    However, this approach rarely works. If your users run their own apps, you really want run separate instances of Tomcat so you can sandbox the apps better. e.g. One app running out of memory doesn't kill all other apps.

    If you provide the app, you can just use one host (defaultHost). You can get the domain name from Host header and do whatever domain-specific stuff in your code.