Programmatic equivalents of web.xml sections for Tomcat

Most documentation for J2EE configuration is based on having a web.xml file, but I want to configure my Tomcat programmatically. Here are some of the things I have found out.

Please use the comments below to correct what I got wrong, and mention equivalents for other parts of web.xml.

Getting started

<web-app ...

in code becomes something like:

import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
Tomcat tomcat = new Tomcat();
Context context = tomcat.addContext( "", "WebContent" );

Adding a Servlet

<web-app ...

in code becomes something like:

Class servletClass = MyServlet.class;
// MyServlet extends javax.servlet.http.HttpServlet 
String servletName = servletClass.getSimpleName(); // Or something else if you like
Tomcat.addServlet( context, servletName, servletClass.getName() );
context.addServletMapping( "/foo/*", servletName );

Adding a filter

<web-app ...

in code becomes something like:

import org.apache.catalina.deploy.FilterDef;
import org.apache.catalina.deploy.FilterMap;
Class filterClass = MyFilter.class;
// MyFilter implements javax.servlet.Filter
String filterName = filterClass.getSimpleName(); // Or something else if you like
FilterDef def = new FilterDef();
def.setFilterName( filterName );
context.addFilterDef( def );
FilterMap map = new FilterMap();
map.setFilterName( filterName );
map.addURLPattern( "/bar/*" );
context.addFilterMap( filterMap );

Adding a Listener

<web-app ...

in code becomes something like:

context.addApplicationListener( MyContextListener.class.getName() );
// MyContextListener implements javax.servlet.ServletContextListener

This is for a ServletContextListener: it may be similar for other listeners, but I’m not sure.

4 thoughts on “Programmatic equivalents of web.xml sections for Tomcat”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.