简体   繁体   English

我怎样才能在Java中提供URL的绝对路径

[英]How can I get absolute path of providing url in java

I want to get absolute path of url. 我想获取url的绝对路径。 For example, http://localhost:8080 will give me tomcat home page available in root directory. 例如, http:// localhost:8080将为我提供根目录中可用的tomcat主页。 How can I get absolute path of tomcat root directory by providing its url http://localhost:8080 in java. 如何通过在Java中提供其URL http:// localhost:8080来获取tomcat根目录的绝对路径。

I found similar question but not found satisfactory answer so I am posting problem here. 我发现了类似的问题,但没有找到满意的答案,所以我在这里发布问题。

You could use javax.servlet.ServletContext.getRealPath(java.lang.String) , although there are some cases where it will not work. 您可以使用javax.servlet.ServletContext.getRealPath(java.lang.String) ,尽管在某些情况下它不起作用。

From the API documentation : API文档中

Gets the real path corresponding to the given virtual path. 获取与给定虚拟路径相对应的真实路径。

For example, if path is equal to /index.html , this method will return the absolute file path on the server's filesystem to which a request of the form http://<host>:<port>/<contextPath>/index.html would be mapped, where <contextPath> corresponds to the context path of this ServletContext. 例如,如果path等于/index.html ,则此方法将返回服务器文件系统上的绝对文件路径,该文件的格式为http://<host>:<port>/<contextPath>/index.html将被映射,其中<contextPath>对应于此ServletContext的上下文路径。

The real path returned will be in a form appropriate to the computer and operating system on which the servlet container is running, including the proper path separators. 返回的实际路径将采用适合运行servlet容器的计算机和操作系统的形式,包括适当的路径分隔符。

Resources inside the /META-INF/resources directories of JAR files bundled in the application's /WEB-INF/lib directory must be considered only if the container has unpacked them from their containing JAR file, in which case the path to the unpacked location must be returned. 仅当容器从包含其的JAR文件中解压缩了应用程序的/WEB-INF/lib目录中捆绑的JAR文件的/META-INF/resources目录内的/META-INF/resources ,才应考虑该资源,在这种情况下,必须向解压缩位置的路径被退回。

This method returns null if the servlet container is unable to translate the given virtual path to a real path. 如果servlet容器无法将给定的虚拟路径转换为真实路径,则此方法返回null。

Parameters: 参数:
path - the virtual path to be translated to a real path path-要转换为真实路径的虚拟路径

Returns: 返回值:
the real path, or null if the translation cannot be performed 真实路径;如果无法执行转换,则为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM