2013-07-17 38 views
1

我其實有PROGRAMM與servlet:Servlet的init和

@WebServlet("/Controler") 
public class Controler extends HttpServlet { 

} 

我需要使用屬性文件:file.properties在我的計劃。加載它,我有一個類:

public class PropLoader { 

    private final static String m_propertyFileName = "file.properties"; 

    public static String getProperty(String a_key){ 

     String l_value = ""; 

     Properties l_properties = new Properties(); 
     FileInputStream l_input; 
     try { 

      l_input = new FileInputStream(m_propertyFileName); // File not found exception 
      l_properties.load(l_input); 

      l_value = l_properties.getProperty(a_key); 

      l_input.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return l_value; 

    } 

} 

我的屬性文件是在WebContent文件夾,我可以訪問它:

String path = getServletContext().getRealPath("/file.properties"); 

但我不能調用其他類論文的方法比servlet ...

我如何訪問PropLoader類中的屬性文件?

+0

好吧,一種選擇是將路徑作爲靜態變量添加到PropLoader類(單類的一種)。我已經看到了一些主要servlet在init()方法中執行這些步驟的情況,因此您將在整個應用程序中提供您的路徑。你只需要確定你正在處理的servlet是在應用程序啓動時加載的。 – Martin

+0

我試過這個解決方案,但servlet無法在propLoader類中實例化路徑,我認爲這是由於init()servlet方法 – Apaachee

回答

2

如果你想從Web應用程序結構中讀取文件,那麼你應該使用ServletContext.getResourceAsStream()。當然,既然你從webapp加載它,你需要引用表示webapp的對象:ServletContext。你可以在你的servlet覆蓋init(),稱getServletConfig().getServletContext()得到這樣的引用,並通過servlet上下文的方法加載該文件:

@WebServlet("/Controler") 
public class Controler extends HttpServlet { 
    private Properties properties; 

    @Override 
    public void init() { 
     properties = PropLoader.load(getServletConfig().getServletContext()); 
    } 
} 

public class PropLoader { 

    private final static String FILE_PATH = "/file.properties"; 

    public static Properties load(ServletContext context) { 
     Properties properties = new Properties(); 
     properties.load(context.getResourceAsStream(FILE_PATH)); 
     return properties; 
    } 
}  

注意某些異常必須進行處理。

另一種解決方案是將文件置於WEB-INF/classes的部署webapp中,並使用ClassLoader加載文件:getClass().getResourceAsStream("/file.properties")。這樣,你不需要參考ServletContext

+0

嗨JB Nizet!對於第二種解決方案,我將我告訴的結果複製/粘貼到Icestari:我的屬性文件位於Eclipse WebContent根文件夾中,'in == null'中包含:InputStream in = Controler.class.getClassLoader()。的getResourceAsStream(m_propertyFileName); '那麼,我不確定要理解你的第一個解決方案 – Apaachee

+0

這就是爲什麼我的回答告訴你,爲了使這個解決方案起作用,文件必須在WEB-INF/classes下。我會編輯我的答案,使第一部分更清晰。 –

+0

與我的屬性文件的結果相同:'WEB-INF/classes/file.properties'或'WEB-INF/file.properties',getResourceAsStream()返回null。 – Apaachee

1

我會推薦使用getResourceAsStream方法(下面的例子)。它需要屬性文件位於WAR類路徑中。

InputStream in = YourServlet.class.getClassLoader().getResourceAsStream(path_and_name); 

問候 欒

+0

感謝您的回答Icestari!我的屬性文件位於Eclipse WebContent根文件夾中,'in == null'中有:'InputStream in = Controler.class.getClassLoader()。getResourceAsStream(m_propertyFileName);' – Apaachee

相關問題