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

3 thoughts on “Programmatically adding and configuring web components

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s