java - ServeletContext.getRealPath(“”) 为什么返回应用的根目录绝对地址?
高洛峰
高洛峰 2017-04-18 10:14:00
0
1
437

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的概念。

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
大家讲道理

======To answer your question, I suddenly encountered a segmentfault and the website crashed. I wrote the answer again====

javax.servlet.ServletContext

is an interface. The specific implementation is implemented by a servlet container, such as tomcat. A method called getRealPath is defined in this interface, and the corresponding implementation is also implemented by various servlet containers. I didn't check the source code of tomcat, only the mock implementation of spring.

@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;
}

In this implementation, you can see that the effect of passing "" and "/" is the same. There is no need to explain more since the code is already there. The implementation of other containers is estimated to be similar.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template