Programmatic equivalents of web.xml sections for Tomcat
February 05, 2015 [j2ee, Java, Programming]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 ... <servlet> ... <servlet-name>MyServlet</servlet-name> <servlet-class>com.example.MyServlet</servlet-class> ... </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/foo/*</url-pattern> </servlet-mapping>
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 ... <filter> <filter-name>MyFilter</filter-name> <filter-class>com.example.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>/bar/*</url-pattern> </filter-mapping>
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 ... <listener> <listener-class>com.example.MyContextListener</listener-class> </listener>
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.