Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

从 request uri 中获取模板路径存在问题,会出现404错误 #41

Closed
subchen opened this issue Dec 7, 2013 · 1 comment
Closed
Assignees
Labels
Milestone

Comments

@subchen
Copy link
Owner

subchen commented Dec 7, 2013

主要是这几个方法的返回值的使用方式问题:

request.getServletPath()
request.getPathInfo()
request.getRequestURI()

其中 request.getRequestURI() 的返回值包含了 request.getContextPath(),所以是相对于网站的根目录的。

下面我们分析 request.getServletPath()request.getPathInfo()

  1. 如果我们的 servlet-mapping 如下配置:

    <servlet-mapping>
      <servlet-name>jetbrick-template</servlet-name>
      <url-pattern>*.jetx</url-pattern>
    </servlet-mapping>

    那么访问: /context/templates/index.jetx

    request.getServletPath() == "/templates/index.jetx"
    request.getPathInfo() == <null>
  2. 如果我们的 servlet-mapping 如下配置:

    <servlet-mapping>
      <servlet-name>jetbrick-template</servlet-name>
      <url-pattern>/*</url-pattern>
    </servlet-mapping>

    那么访问: /context/templates/index.jetx

    request.getServletPath() == ""
    request.getPathInfo() == "/templates/index.jetx"
  3. 如果我们的 servlet-mapping 如下配置:

    <servlet-mapping>
      <servlet-name>jetbrick-template</servlet-name>
      <url-pattern>/template/*</url-pattern>
    </servlet-mapping>

    那么访问: /context/templates/index.jetx

    request.getServletPath() == "/templates"
    request.getPathInfo() == "/index.jetx"

总结

所以,我们要获取相对于 request.getContextPath() 的路径,我们可以使用如下的代码:

String uri = request.getServletPath();
String pathInfo = request.getPathInfo();
if (pathInfo != null && pathInfo.length() > 0) {
    uri = uri + pathInfo;
}

或者:

String uri = request.getRequestURI();
String contextPath = request.getContextPath();
if (contextPath != null && contextPath.length() > 0) {
    uri = uri.substring(contextPath.length());
}
@ghost ghost assigned subchen Dec 7, 2013
@subchen subchen closed this as completed in 51e54be Dec 7, 2013
@subchen
Copy link
Owner Author

subchen commented Dec 10, 2013

Regression issue by #23

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant