Question

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.

Was it helpful?

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.

OTHER TIPS

pattern can either end in an asterisk or start with one (to denote a file extension mapping).

more info at:

http://javapapers.com/servlet/what-is-servlet-mapping/#&slider1=1

The url-pattern specification:

        *A string beginning with a ‘/’ character and ending with a ‘/*’ 
        suffix is used for path mapping.
        *A string beginning with a ‘*.’ prefix is used as an extension mapping.
        *A string containing only the ’/’ character indicates the "default" 
        servlet of the application. In this case the 
        servlet path is the request URI minus the context path and the path 
        info is null.
        *All other strings are used for exact matches only.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top