我可以在servlet映射中组合这些url模式吗?

时间:2012-01-27 16:03:35

标签: tomcat servlets url-pattern

我需要支持/ {servlet} / history,并且有许多需要支持它的servlet。我正在使用Tomcat,FWIW。

以下是有效的,但我想知道是否有办法将所有模式组合成一行,并避免为每个需要支持历史模式的servlet添加url-pattern。我尝试了几种选择但都失败了。

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

感谢。

2 个答案:

答案 0 :(得分:3)

为了只有一个网址格式,您需要指定公共前缀(文件夹)模式,如/history/*或后缀(扩展名)模式,如*.history。您不能在*/history/*两侧都使用带有通配符匹配的网址格式。最好的办法是将历史servlet映射到/history/*并相应地更改URL,例如/history/aDifferentServlet(此部分可由历史servlet中的request.getPathInfo()使用)。

如果更改URL是不可取的,那么只要请求URI与Filter模式匹配,就需要创建*/history/*或重写它们转发到历史servlet的servlet。

答案 1 :(得分:0)

模式可以以星号结尾或以1开头(表示文件扩展名映射)。

更多信息:

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.