Servlet Real Path

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

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.

e.g. www.example.com/blog/test-file.html -> /usr/share/tomcat7/webapps/blog/test-file.html

I tried the following:

 public String realPath(HttpServletRequest request, ServletContext servletContext){     String requestURI = request.getRequestURI();     String realPath = servletContext.getRealPath(requestURI);     return realPath; }

However this returns

/usr/share/tomcat7/webapps/blog/blog/test-file.html

What is the correct way to do this?

回答1:

Short answer

To get the result you want, use HttpServletRequest#getServletPath() method as an argument to getRealPath() method.

This is the closest to what you want to accomplish (read the note below).


Explanation

The reason you're getting such path (with double blog) is that you're using the result returned by the getRequestURI() method.

The getRequestURI() method returns the path starting with application context. In your case it will be:
/blog/test-file.html

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/

So the resulting path is:
/usr/share/tomcat7/webapps/blog/blog/test-file.html

That is the reason of your double blog issue.


IMPORTANT NOTE

DISCLAIMER
Maybe the OP is already aware of the information written below, but it is written for the sake of completeness.

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.

Also quote from the ServletContext.getRealPath(String) documentation (emphasis mine):

Gets the real path corresponding to the given virtual path.



转载请标明出处:Servlet Real Path
文章来源: Servlet Real Path
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!