Java – Servlet Mapping: Is it possible to add servlet mappings at runtime

javaservletstomcat

Is it possible to add a servlet mapping at runtime? either through a ContextListener or within a Servlet's init() method?

Within the application I am using, all requests are handled through a single Servlet and their mappings are defined in the web.xml file. The number of mappings are increasing and adding a new mapping requires a new release.

Mapping the servlet to /* would not work since requests dispatched to JSPs and static content would also be routed to this Servlet.

Using a filter might be an option nevertheless, it will add a requirement for the filter to know what path to prefix to the RequestDispatcher.

For example:

Dispatcher Servlet Mapping

<servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/action/*</url-pattern>
</servlet-mapping>

Routing Filter Definition

<filter>
    <filter-name>RoutingFilter</filter-name>
    <filter-class>com.ssv.web.filter.RoutingFilter</filter-class>
    <init-param>
        <param-name>exclude</param-name>
        <param-value>/static/**:/action/**:/**/*.jsp</param-value>
    </init-param>
    <init-param>
        <param-name>dispatcher-prefix</param-name>
        <param-value>/action/**</param-value>
    </init-param>
</filter>

In the above example, I would like to skip creating the filter, the filter mapping, and the servlet mapping and instead dynamically define mappings in a ContextListener.

I'm using Tomcat.

Best Answer

In servlet 3.0 (tomcat 7) it is possible: ServletContext.addServlet(..)

But in your case it may be wiser not to do that. Spring's DispatcherServlet for example is mapped to /*. It forwards to JSPs internally, and handles requests in its own non-servlet components, so that it doesn't need to register them dynamically. Take a look at spring-mvc anyway, even if you don't end up using it.

Related Topic