2016-03-08 105 views
0

我一直试图通过使用上下文的主机和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应用程序代码才能正常工作?

回答

1

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

此,主要有:

返回内 的Web应用程序,其最长的子路径提供的路径 参数匹配的所有路径的资源类目录清单。

所以,让你的WEB-INF文件夹内的所有内容,你可以这样做:

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

然后通过paths迭代来获得相关资源。资源结尾/表示一个子目录。

0

我设法通过使用ServletContext.getResourceAsStream()来解决这个问题,它可以用来获得指定资源的InputStream

就我所知,这只是Tomcat本身执行其web.xml文件读取的方式。必须指出的是,此方法在LifeCycle事件CONFIGURE_START_EVENT而非BEFORE_START_EVENT时有效。

+0

那么你的问题是非常误导。阅读标题。 –

相关问题