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
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
... MyServlet com.example.MyServlet ...MyServlet /foo/* 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
MyFilter com.example.MyFilter MyFilter /bar/* 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
com.example.MyContextListener in code becomes something like:
... context.addApplicationListener( MyContextListener.class.getName() ); // MyContextListener implements javax.servlet.ServletContextListenerThis is for a ServletContextListener: it may be similar for other listeners, but I'm not sure.
Originally posted at 2015-02-05 12:48:56+00:00. Automatically generated from the original post : apologies for the errors introduced.