Search code examples
javaclassweb-applicationsservletconfig

Dynamically add a servlet to the servletConfig


I have a Java web application that uses a plugin architecture. I would like to know if anyone has a solution where by one could add a servlet, with serlvet mapping to the servletconfig while the web app is running? The idea being that a class could be added to the /WEB-INF/classes folder and be made active as a servlet without restarting the web app. By the same nature, if the user chooses to remove the "plugin" then have the code remove the class from the the servletconfig.


Solution

  • There is no standard Servlet API to accomplish this.

    You can do this in Tomcat. In your webapp, your master servlet (the one creates others) must implements ContainerServlet so you can get hold of the Wrapper object. Once you have your class file installed, you can make following calls,

    Context context = (Context) wrapper.getParent();
    Wrapper newWrapper = context.createWrapper();
    newWrapper.setName(name);
    newWrapper.setLoadOnStartup(1);
    newWrapper.setServletClass(servletClass);
    context.addChild(newWrapper);
    context.addServletMapping(pattern, name);
    

    These calls create a servlet on the fly. You need to find way to persist this information. You can do this by updating web.xml or write to your own file.