-- Leo's gemini proxy

-- Connecting to republic.circumlunar.space:1965...

-- Connected

-- Sending request

-- Meta line: 20 text/gemini

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 ...
   <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.


Originally posted at 2015-02-05 12:48:56+00:00. Automatically generated from the original post : apologies for the errors introduced.


original post

-- Response ended

-- Page fetched on Sun May 19 04:25:12 2024