查找多servlet映射场景中使用的匹配url-pattern

时间:2012-05-22 08:17:30

标签: java servlets

假设我有一个Java servlet,我想用它来处理两个(或更多)不同的url模式:

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

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

我想知道的是如何从我的代码中告诉我们匹配请求的路径是什么。 (即如果请求是/myapp/yet/another/exact/path我想获得字符串/yet/another/exact/path)。

我想还有一种方法可以区分/ that /前缀/路径/以及与之匹配的内容*如果有人能告诉我应该如何做,那将会很好。

我尝试了String path = req.getRequestURI(),但它也返回了/ myapp部分。

2 个答案:

答案 0 :(得分:9)

HttpServletRequest.getServletPath()返回不包含/*的网址格式,HttpServletRequest.getPathInfo()返回与/*匹配的部分(或null完全匹配)。

答案 1 :(得分:0)

您应该使用:

     /**
     *
     * 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();