【问题标题】:tomcat 5.5 - problem with reading resource filestomcat 5.5 - 读取资源文件的问题
【发布时间】:2008-11-18 11:39:47
【问题描述】:

我使用 Tomcat 5.5 作为我的 servlet 容器。我的 Web 应用程序通过 .jar 部署,并且在其 WEB-INF 目录下有一些资源文件(带有字符串和配置参数的文本文件)。 Tomcat 5.5 在 ubuntu linux 上运行。使用文件阅读器读取资源文件:
fr = new FileReader("messages.properties");

问题是有时 servlet 找不到资源文件,但如果我重新启动它几次它可以工作,然后再过一段时间它会停止工作。 有人可以建议从 servlet 读取资源字符串的最佳方法是什么?或者这个问题的解决方法? 将资源文件放在 WEB-INF/classes 下也无济于事。

【问题讨论】:

    标签: java tomcat servlets resources


    【解决方案1】:

    如果您尝试从可识别 Servlet 的类(例如 ContextListener 或其他生命周期侦听器)访问此文件,则可以使用 ServletContext 对象获取资源的路径。

    这三个大致相等。 (不要将 getResourceAsStream 与 ClassLoader 类提供的混淆。它们的行为非常不同)

    void myFunc(ServletContext context) {
       //returns full path. Ex: C:\tomcat\5.5\webapps\myapp\web-inf\message.properties 
       String fullCanonicalPath = context.getRealPath("/WEB-INF/message.properties");
    
       //Returns a URL to the file. Ex: file://c:/tomcat..../message.properties
       URL urlToFile = context.getResource("/WEB-INF/message.properties");
    
       //Returns an input stream. Like calling getResource().openStream();
       InputStream inputStream = context.getResourceAsStream("/WEB-INF/message.properties");
       //do something
    }
    

    【讨论】:

      【解决方案2】:

      我猜问题是您尝试使用相对路径来访问文件。 使用绝对路径应该会有所帮助(即“/home/tomcat5/properties/messages.properties”)。

      但是,解决这个问题的通常方法是使用 ClassLoader 的 getResourceAsStream 方法。将属性文件部署到“WEB-INF/classes”将使其可用于类加载器,您将能够访问属性流。

      未经测试的原型代码:

      Properties props = new Properties();
      
      InputStream is =
      getClass().getClassLoader().getResourceAsStream("messages.properties");
      
      props.load(is);
      

      【讨论】:

        【解决方案3】:

        如果你使用

        new FileReader("message.properties");
        

        然后 FileReader 将尝试从基本目录读取该文件 - 在 Tomcat 中可能是 /bin 文件夹。

        正如 diciu 所说,使用绝对路径或将其作为资源加载到类加载器中。

        【讨论】:

          【解决方案4】:

          我使用以下代码从 servlet 中加载属性文件:

          public void init(ServletConfig config) throws ServletException {
              String pathToFile = config.getServletContext().getRealPath("")
                  + "/WEB-INF/config.properties";
              Properties properties = new Properties();
              properties.load(new FileInputStream(pathToPropertiesFile));
          }
          

          这适用于 Tomcat 6.0

          【讨论】:

            【解决方案5】:

            我确实用于 Jboss Seam:

            ServletLifecycle.getServletContext().getRealPath("")

            【讨论】:

            • 这与提出的问题有什么关系?
            猜你喜欢
            • 1970-01-01
            • 2012-03-25
            • 1970-01-01
            • 2011-09-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-11-24
            • 2016-06-17
            相关资源
            最近更新 更多