Search code examples
tomcatclassloader

To customize the webapp class loader for all the webapps


How to customize the webapp class loader for all the webapps in tomcat using a common webappclassloader?

I saw that I can extend class loader and add it in the context tag for each and every webapp, is there a way to put this as common classloader for all the webapps and also where I should place this classloader .class file?

Thanks


Solution

  • You can place the custom class loader in $CATALINA_HOME/lib.

    To replace the default loader for all webapps, a convenient solution is modifying $CATALINA_HOME/conf/context.xml

    <?xml version='1.0' encoding='utf-8'?>
    <Context>
        <Loader className="test.loader.MyWebappLoader" /><!-- add this element -->
    </Context>
    

    Here is a sample code:

    package test.loader;
    import org.apache.catalina.loader.WebappLoader;
    public class MyWebappLoader extends WebappLoader {
        public MyWebappLoader() {
            System.err.println("!! create MyWebappLoader !!");
        }
        public MyWebappLoader(ClassLoader parent) {
            super(parent);
            System.err.println("!! create MyWebappLoader !!");
        }
    }
    

    For more detail, you can read Tomcat document - The Loader Component. It work on Tomcat 7~9.