我一直在尝试获取通过使用主机的应用程序库和上下文的文档库来部署的应用程序的上下文根。
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文件夹中的自定义配置文件。
在进一步研究时,我发现了以下简单的方法来访问位于应用程序文件夹中的资源。
How to get file system path of the context root of any application
但是,当我使用此处定义的方法时,上下文根始终会得到一个空值。
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应用程序
论点。
因此,要获取WEB-INF
文件夹中的所有内容,可以执行以下操作:
Set<String> paths = servletContext.getResourcePaths("/WEB-INF/");
然后遍历
paths
以获得相关资源。以/
结尾的资源表示一个子目录。