繁体   English   中英

在Tomcat中访问应用程序上下文根目录中的文件

[英]Accessing a file within the context root of an application in Tomcat

我一直在尝试获取通过使用主机的应用程序库和上下文的文档库来部署的应用程序的上下文根。

try {
    if (context != null) {
        //  Value of the following variable depends on various conditions. Sometimes you get just the webapp
        //  directory name. Sometime you get absolute path the webapp directory or war file.
        String webappFilePath;
        Host host = (Host) context.getParent();
        String appBase = host.getAppBase();
        File canonicalAppBase = new File(appBase);
        if (canonicalAppBase.isAbsolute()) {
            canonicalAppBase = canonicalAppBase.getCanonicalFile();
        } else {
            canonicalAppBase = new File(PathUtils.getCatalinaBase().toString(), appBase).getCanonicalFile();
        }

        String docBase = context.getDocBase();
        File webappFile = new File(docBase);
        if (webappFile.isAbsolute()) {
            webappFilePath = webappFile.getCanonicalPath();
        } else {
            webappFilePath = (new File(canonicalAppBase, docBase)).getPath();
        }
        return Paths.get(webappFilePath);
    } else {
        throw new ApplicationServerException("Context cannot be null");
    }
} catch (IOException ex) {
    throw new ApplicationServerException("Error while generating webapp file path", ex);
}

访问上下文根目录的目的是访问我添加到/ WEB-INF文件夹中的自定义配置文件。

在进一步研究时,我发现了以下简单的方法来访问位于应用程序文件夹中的资源。

如何获取任何应用程序上下文根的文件系统路径

但是,当我使用此处定义的方法时,上下文根始终会得到一个空值。

Path contextWebAppDescriptor = Paths.
                        get(context.getServletContext().getRealPath("/"), Constants.WEBAPP_RESOURCE_FOLDER,
                                Constants.WEBAPP_DESCRIPTOR);

请考虑两个常量:

public static final String WEBAPP_RESOURCE_FOLDER = "WEB-INF";
public static final String WEBAPP_DESCRIPTOR = "wso2as-web.xml";

我是否误解了此方法的正确用法? 我们只能使用该方法吗

context.getServletContext().getRealPath("/");

仅在网络应用程序代码内才能正常运行?

更好的方法,恕我直言,将使用ServletContext.getResourcePaths()方法。

这本质上是:

返回类似于目录的目录,列出了Web应用程序中资源的所有路径,这些路径的最长子路径与提供的path参数匹配。

因此,要获取WEB-INF文件夹中的所有内容,可以执行以下操作:

Set<String> paths = servletContext.getResourcePaths("/WEB-INF/");

然后遍历paths以获取相关资源。 /结尾的资源表示子目录。

我设法通过使用ServletContext.getResourceAsStream()解决了此问题,该ServletContext.getResourceAsStream()可用于获取指定资源的InputStream

据我所知,这仅仅是Tomcat本身执行web.xml读取的方式。 必须注意的是,此方法在LifeCycle事件CONFIGURE_START_EVENT而非BEFORE_START_EVENT上有效。

暂无
暂无

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

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