Dynamic Servlet Registration

One of the cool features introduces by Java EE 6 is Dynamic Registration of Servlets and Filters at application startup. This can be really useful if you are building your own framework but I guess for developers too can benefit from it.

In order to do that, you can use some new methods introduced in the ServletContext class which are able to programmatically add servlets and servlet filters to a web application during startup. The methods are addServlet() method to add a servlet to the web application, and the corresponding addFilter() method to add a servlet filter.

Here’s an example of it which dynamically registers a Servlet as soon as the ServletContextListener is triggered:


public class TestServletContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {

        ServletContext sc = sce.getServletContext();

        // Register Servlet
        ServletRegistration sr = sc.addServlet("DynamicServlet",
        sr.setInitParameter("servletInitName", "servletInitValue");

The same strategy cam be used to register a Filter named DynamicFilter bound to the class com.sample.TestFilter:

// Register Filter
FilterRegistration fr = sc.addFilter("DynamicFilter","com.sample.TestFilter");
fr.setInitParameter("filterInitName", "filterInitValue");
                                     true, "DynamicServlet");