我一直试图通过使用上下文的主机和doc基础的应用程序库来获取正在部署的应用程序的上下文根。在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文件夹的自定义配置文件。
当进一步研究时,我发现了以下访问位于应用文件夹内的资源的简单方法。
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("/");
只在Web应用程序代码才能正常工作?
那么你的问题是非常误导。阅读标题。 –