epeleg
epeleg

Reputation: 10915

finding the matched url-pattern used in a multiple servlet-mapping scenario

Suppose I have a Java servlet that I want to use for two (or more) different url-patterns:

  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/this/exact/path</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/that/prefix/path/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/yet/another/exact/path</url-pattern>
  </servlet-mapping>

MyServlet will be called for any of:

/this/exact/path
/yet/another/exact/path
/that/prefix/path/param1
/that/prefix/path/param2.html

what I want to know is how can I tell from inside my code what was the path for which the request was matched for . (i.e. if the request was made to /myapp/yet/another/exact/path i want to get the string /yet/another/exact/path).

I guess also that there should be a way to differentiate between the /that/prefix/path/ and what ever was matched with the * It would be nice if someone could tell me how this should be done.

I tried String path = req.getRequestURI() but it also returns the /myapp part.

Upvotes: 2

Views: 5683

Answers (2)

axtavt
axtavt

Reputation: 242696

HttpServletRequest.getServletPath() returns the URL pattern excluding /*, and HttpServletRequest.getPathInfo() returns the part matched by /* (or null for exact match).

Upvotes: 9

shem
shem

Reputation: 4712

You should use:

     /**
     *
     * Returns any extra path information associated with
     * the URL the client sent when it made this request.
     * The extra path information follows the servlet path
     * but precedes the query string and will start with
     * a "/" character.
     *
     * <p>This method returns <code>null</code> if there
     * was no extra path information.
     *
     * <p>Same as the value of the CGI variable PATH_INFO.
     *
     *
     * @return      a <code>String</code>, decoded by the
     *          web container, specifying 
     *          extra path information that comes
     *          after the servlet path but before
     *          the query string in the request URL;
     *          or <code>null</code> if the URL does not have
     *          any extra path information
     *
     */
    public String getPathInfo();

Upvotes: 0

Related Questions