Programmatically adding and configuring web components


The ability to programmatically add a servlet and filter to a context is useful for framework developers.


package com.pkg.servlet30;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebListener;

@WebListener
public class SimpleServletContextListener implements ServletContextListener {

 @Override
 public void contextInitialized(ServletContextEvent sce) {
 ServletContext context = sce.getServletContext();

 String simpleServletName = "simpleServlet";
 String simpleFilterName = "simpleFilter";

 Map<String, String> initParams = new HashMap<String, String>();
 initParams.put("param1", "value1");
 initParams.put("param2", "value2");

 String[] urlPatterns = new String[]{"/simple"};

 ServletRegistration.Dynamic addServlet = context.addServlet(simpleServletName, NewServlet.class);
 addServlet.addMapping(urlPatterns);
 addServlet.setInitParameters(initParams);

 context.addFilter(simpleFilterName, NewFilter.class);

 }

 @Override
 public void contextDestroyed(ServletContextEvent sce) {

 }

}

 

The code is straightforward. It acquires the reference to ServletContext and makes use of the methods addServlet(), addMapping(), setInitParameters() and addFilter() for dynamically adding web components.

Advertisements