ServletContext getRealPath method - what is a virtual path?

浪子不回头ぞ 提交于 2019-12-07 11:50:03

问题


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)?


回答1:


ServletContext.getRealPath(String s) returns the real file system path. The input string is interpreted relative your Web Applications' Context Path.

In e.g. eclipse this is typically the folder WebContent inside your Web Application project (it is possible to customize that). After building a WAR file out of the project, you'll realize that the WebContent folder disappeared, so on the server the input string is interpreted relative to the WAR files' folder (or the .war library - this depends whether you explode the WAR during deployment or not).

A note on security

This method should (not must) only be used in case you want to access a file on the serverside. Typical scenario is parsing a configuration file during startup. Just keep in mind to never let the caller of your application know the real file system path of a given resource.




回答2:


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:

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



来源:https://stackoverflow.com/questions/12523848/servletcontext-getrealpath-method-what-is-a-virtual-path

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