簡體   English   中英

tomcat 5.5 - 讀取資源文件的問題

[英]tomcat 5.5 - problem with reading resource files

我正在使用Tomcat 5.5作為我的servlet容器。 我的Web應用程序通過.jar部署,並在其WEB-INF目錄下有一些資源文件(帶有字符串和配置參數的文本文件)。 Tomcat 5.5在ubuntu linux上運行。 使用文件讀取器讀取資源文件:
fr = new FileReader("messages.properties");

問題是有時servlet找不到資源文件,但如果我重新啟動它幾次就可以了,那么經過一段時間它再次停止工作。 有人可以建議從servlet讀取資源字符串的最佳方法是什么? 或解決此問題的方法? 將資源文件放在WEB-INF / classes下也無濟於事。

如果您嘗試從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
}

我猜你的問題是你正在嘗試使用相對路徑來訪問該文件。 使用絕對路徑應該有幫助(即“/home/tomcat5/properties/messages.properties”)。

但是,此問題的常見解決方案是使用ClassLoader的getResourceAsStream方法。 將屬性文件部署到“WEB-INF / classes”將使其可用於類加載器,您將能夠訪問屬性流。

未經測試的原始代碼:

Properties props = new Properties();

InputStream is =
getClass().getClassLoader().getResourceAsStream("messages.properties");

props.load(is);

我使用以下代碼從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

如果你使用

new FileReader("message.properties");

然后FileReader將嘗試從基目錄中讀取該文件 - 在Tomcat中可能是/ bin文件夾。

正如diciu所提到的,使用絕對路徑或將其作為類加載器的資源加載。

我用過Jboss Seam:

ServletLifecycle.getServletContext().getRealPath("")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM