Drux
Drux

Reputation: 12670

Mapping two servlets in web.xml where one URL pattern is substring of the other

I have a web application where I would like to tie a JSP to address http://host:port/status and a servlet to addresses like http://host:port/status/.... Is this possible? According to this article it should be possible ("container prefers an exact path match over a wildcard path match") at least for some containers and the Java Servlet Specification contains similar examples (albeit without wildcard, on p. 12-123 in April 2013 version), but if I try the following in web.xml it appears as if the JSP is never called and all requests (also to http://host:port/status) are routed to the servlet. My JSP and servlet are hosted on Google App Engine.

<servlet>
    <servlet-name>Status</servlet-name>
    <jsp-file>/Status.jsp</jsp-file>
</servlet>
<servlet-mapping>
    <servlet-name>Status</servlet-name>
    <url-pattern>/status</url-pattern>
</servlet-mapping>
<servlet>
    <servlet-name>StatusUpload</servlet-name>
    <servlet-class>com.example.StatusUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>StatusUpload</servlet-name>
    <url-pattern>/status/*</url-pattern>
</servlet-mapping>

Upvotes: 2

Views: 659

Answers (1)

developerwjk
developerwjk

Reputation: 8659

Instead of mapping the same url to two different JSPs/Servlets in web.xml you can use a URL Rewriting filter like Tuckey UrlRewriteFilter which uses a configuration file urlrewrite.xml which would also be placed in WEB-INF. It uses regex in the rules.

These two rules should do what you want:

      <rule>
        <from>^/status$</from>
        <to>/Status.jsp</to>
      </rule>
      <rule>
        <from>^/status/(.*)$</from>
        <to>/StatusUpload/?param=$1</to>
      </rule>

Then in WEB-INF you would not map the JSP anymore but would map the Servlet to StatusUpload. When the user goes to /status/postfix the URL Rewriting filter will forward to the servlet (with the postfix part passed as a parameter) in the backend without the address the user sees in the address bar changing.

Upvotes: 1

Related Questions