2

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
DD.
  • 21,498
  • 52
  • 157
  • 246
  • 1
    You're assuming that there is a real path for the file which does not need be true. It is possible that a web application container runs out of the `.jar` file without having a native file path. – Uwe Plonus Jul 01 '13 at 08:26
  • @UwePlonus Thats irrelevant for the question I'm asking. – DD. Jul 01 '13 at 08:30

1 Answers1

4

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.

Community
  • 1
  • 1
informatik01
  • 16,038
  • 10
  • 74
  • 104