java - ServeletContext.getRealPath(“”) 为什么返回应用的根目录绝对地址?
问题描述
getRealPath
java.lang.String getRealPath(java.lang.String path)
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&... would be mapped, where <contextPath> corresponds to the context path of this ServletContext.
上面是API的解释,我疑惑的是这个virtual path。
一般的用法是serveletContext.getRealPath(/),/可以理解为,应用的根目录,那么 呢?
希望有大神能,详细的解释这个virtual path的概念。
=====回答你这个问题突然遇到segmentfault网站挂了答案又重新写一遍====
javax.servlet.ServletContext
是一个接口。具体实现由servlet容器来实现,比如tomcat。在这个接口中定义了一个方法叫getRealPath,相应的实现也是有各个servlet容器来实现的。我没有查看tomcat的源码,只看了spring的mock实现。
@Override
public String getRealPath(String path) {
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
try {
return resource.getFile().getAbsolutePath();
}
catch (IOException ex) {
logger.warn("Couldn't determine real path of resource " + resource, ex);
return null;
}
}
protected String getResourceLocation(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
return this.resourceBasePath + path;
}
在这个实现中可以看到传入和传入/效果是一样,代码都有了就不用在多解释了吧。其他容器的实现估计也差不多。
这篇关于java - ServeletContext.getRealPath(“”) 为什么返回应用的根目录绝对地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!