ServletContext getRealPath method - what is a virtual path?

KyelJmD picture KyelJmD · Sep 21, 2012 · Viewed 16.4k times · Source

I am reading the documentation for the getRealPath(String s) and I became confused when I read this statement

Returns a String containing the real path for a given virtual path. For example, the path /index.html returns the absolute file path on the server's filesystem would be served by a request for http://host/contextPath/index.html, where contextPath is the context path of this ServletContext..

What is a virtual path? let's say I am inside in my deployment environment and when I say getRealPath("index.html") does this usually points to the WEB-INF directory? or does getRealPath() starts reading the root directory(inside the folder name of the web app)?

Answer

Jops picture Jops · May 5, 2013

The paths of resources you access from within the web container are all virtual paths. Their virtual root is the base folder of the web application. But in the actual operating system where they reside, they will be in a "concrete" location for sure. getRealPath gives you that path.

Say you have a jsp named index.jsp:

enter image description here

enter image description here

Take note that whenever you use this, you're creating cracks on the portability of your web application.