【问题标题】:How I can specify directories in war file?如何在war文件中指定目录?
【发布时间】:2011-01-18 07:05:20
【问题描述】:

我是 servlet 的新手。我在 servlet.then 中使用以下代码部署到 Jboss 4.1 。 backup_database_configuration_location 是属性文件的位置。但是找不到。如何在 war 文件中指定目录? 提前谢谢大家

try {
  backupDatabaseConfiguration = new Properties();
  FileInputStream backupDatabaseConfigurationfile = new FileInputStream(backup_database_configuration_location));
  backupDatabaseConfiguration.load(backupDatabaseConfigurationfile);
  backupDatabaseConfigurationfile.close();
} catch (Exception e) {
  log.error("Exception while loading backup databse configuration ", e);
  throw new ServletException(e);
}

【问题讨论】:

    标签: java deployment servlets jboss directory


    【解决方案1】:

    您的属性文件位于何处?它是直接在硬盘中的某个位置,还是打包在 JAR 文件中?

    您可以尝试使用getResourceAsStream() 方法检索文件:

    configuration = new Properties();
    configuration.load(MyClass.class.getResourceAsStream(backup_database_configuration_location));
    

    (或者当然,将MyClass替换为您当前的班级名称)

    【讨论】:

    • 这是我使用的方法,但有一些需要注意的事项: a) 您应该在 .load 方法之后关闭 InputStream。 b) 从一个类中,getResourceAsStream 将相对于该 ClassLoader。这意味着如果您的文件位于 /WEB-INF/classes/com/example/config.properties ,则必须将“/com/example/config.properties”传递给getResourceAsStream。
    • @Clinton 对于这一点:是的,当然。我也没有写try { } catch 块;)
    【解决方案2】:

    如果放在webcontent中,则使用ServletContext#getResourceAsStream():

    InputStream input = getServletContext().getResourceAsStream("/WEB-INF/file.properties"));
    

    getServletContext() 方法继承自 HttpServlet。只需在 servlet 中按原样调用即可。

    如果放在类路径中,则使用ClassLoader#getResourceAsStream():

    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.properties");
    

    Class#getResourceAsStream() 的不同之处在于您不依赖于加载类的类加载器(如果该类实际上是例如打包在 JAR 中的实用程序类,则它可能与线程正在使用的类加载器不同并且特定的类加载器可能无法访问某些类路径)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多