Dynamic Registration of Servlets and Filters at application startup

Recently I read about one of the nice feature of JAVA EE 6 - Dynamic Registration of Servlets and Filters at application startup.

I then thought of use cases around this feature. 
I think, this is mostly desinged for framework creators but developers could also get benefits from this.

You can use this fefature by using 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, which dynamically registers a Servlet as soon as the ServletContextListener is triggered:

//Register Servlet
public class MyServletContextListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext sc = sce.getServletContext();
        // Register Servlet here
        ServletRegistration sr = sc.addServlet("DynamicServlet",
        sr.setInitParameter("servletInitParamName", "servletInitParamValue");

The same steps can be used to register a Filter named MyDynamicFilter bound to the class com.sample.TestFilter:

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

Would be great if readers of this post, could suggest creative use cases which could add useful functionality to an applications.

No comments: