Servlet真实路径 [英] Servlet Real Path
问题描述
我正在目录博客下运行一个webapp。 (例如www.example.com/blog)。
I am running a webapp under the directory blog. (e.g. www.example.com/blog).
我想获得请求的真实文件系统路径。
I would like to get the real filesystem path of a request.
例如www.example.com/blog/test-file.html - >
/usr/share/tomcat7/webapps/blog/test-file.html
e.g. www.example.com/blog/test-file.html -> /usr/share/tomcat7/webapps/blog/test-file.html
我尝试了以下内容:
public String realPath(HttpServletRequest request, ServletContext servletContext){
String requestURI = request.getRequestURI();
String realPath = servletContext.getRealPath(requestURI);
return realPath;
}
但是这会返回
/usr/share/tomcat7/webapps/blog/blog/test-file.html
/usr/share/tomcat7/webapps/blog/blog/test-file.html
这样做的正确方法是什么?
What is the correct way to do this?
推荐答案
简答
要获得所需的结果,请使用 HttpServletRequest#getServletPath()
方法作为 getRealPath()
方法的参数。
这是你想要完成的最接近的(阅读下面的注释)。
This is the closest to what you want to accomplish (read the note below).
您获得此类路径的原因(使用双博客
)就是您'重新使用 getRequestURI()方法返回的结果。
The reason you're getting such path (with double blog
) is that you're using the result returned by the getRequestURI() method.
getRequestURI()方法返回以应用程序上下文开头的路径。在您的情况下,它将是:
/blog/test-file.html
The getRequestURI() method returns the path starting with application context. In your case it will be:
/blog/test-file.html
然后, getRealPath()方法将 getRequestURI()方法返回的字符串附加到文件夹的实际/物理路径,其中您的应用程序驻留在文件系统上,在您的情况下是:
/ usr / share / tomcat7 / webapps / blog /
What happens then, the getRealPath() method appends the string returned by getRequestURI() method to the real/physical path to the folder, where you application resides on the file system, which in your case is:
/usr/share/tomcat7/webapps/blog/
因此产生的路径是:
/usr/share/tomcat7/webapps/blog/blog/test-file.html
这是您的双博客
问题的原因。
That is the reason of your double blog
issue.
免责声明
也许OP是我已经知道下面写的信息了,但这是为了完整起见而写的。
你想要获得的真实路径不是意味着,您正在获取文件系统上的真实路径。 web.xml <中配置的 url-pattern
/ em>(或者如果你在相关的注释中使用Servlet 3.0+)实际上是一个逻辑/虚拟路径,它可能与文件系统上的实际物理路径有关,也可能没有,即指定的模式(路径)不需要物理存在。
The real path you are trying to get does not mean you are getting, well, the real path on your file system. The url-pattern
configured in web.xml (or if you're using Servlet 3.0+ in the related annotation) is actually a logical/virtual path, which may or may not relate to the actual, physical path on a file system, i.e. the patterns (paths) specified does not need to exist physically.
同样引用 ServletContext.getRealPath(String)文档(强调我的) :
Also quote from the ServletContext.getRealPath(String) documentation (emphasis mine):
获取与给定的虚拟路径对应的实际路径。
这篇关于Servlet真实路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!