2

假设我有一个 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/prefix/path/ 和曾经与 * 匹配的内容如果有人能告诉我应该如何完成这将是很好的。

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

4

2 回答 2

9

HttpServletRequest.getServletPath()返回不包括 的 URL 模式/*,并HttpServletRequest.getPathInfo()返回匹配的部分/*(或null精确匹配)。

于 2012-05-22T08:27:06.793 回答
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();
于 2012-05-22T08:19:45.613 回答