Search code examples
tomcatservletsurl-pattern

Can I combine these url-patterns in a servlet-mapping?


I have a requirement to support /{servlet}/history, and have many servlets that need to support this. I'm using Tomcat, FWIW.

The following works, but I'm wondering if there's a way to combine all patterns into one line and avoid adding a url-pattern for every servlet that needs to support the history pattern. I've tried several options and failed.

<servlet>
    <servlet-name>History</servlet-name>
    <servlet-class>com.foo.HistoryServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>History</servlet-name>
    <url-pattern>/aDifferentServlet/history/*</url-pattern>
    <url-pattern>/someOtherOne/history/*</url-pattern>
    <url-pattern>/anotherExample/history/*</url-pattern>
</servlet-mapping>
...
<servlet>
    <servlet-name>aDifferentServlet</servlet-name>
    <servlet-class>com.foo.aDifferentServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>aDifferentServlet</servlet-name>
    <url-pattern>/aDifferentServlet/*</url-pattern>
</servlet-mapping>
...

Thanks.


Solution

  • In order to have only one URL pattern, you'd need to specify a common prefix (folder) pattern like /history/* or a suffix (extension) pattern like *.history. You cannot have an URL pattern with wildcard matches on both sides like */history/*. Your best bet is to have the history servlet mapped on /history/* and change the URLs accordingly to for example /history/aDifferentServlet (this part is then available by request.getPathInfo() in the history servlet).

    If changing the URLs is undesireable, you'd need to create a Filter or rewrite the servlets that they forward to the history servlet whenever the request URI matches the */history/* pattern.