2012-10-02 34 views
16

可能重複:
How to load a .properties file into a jsp如何使用屬性文件在JSP

我想用我的屬性文件在JSP中,但它不會正常工作,並且拋出一個錯誤

Error: myproperties.properties (The system cannot find the file specified) 

在這裏我想訪問我的財產文件:

<% 
try 
{ 
    FileInputStream fis = new FileInputStream("myproperties.properties"); 

    Properties p = new Properties(); 
    p.load(fis); 
    String LogFileName = p.getProperty("NameOfLogFile"); 
    out.println(LogFileName); 

} 
catch (Exception e) 
{// Catch exception if any 
    out.println(e.getMessage()); 
} 

我嘗試過很多方式來訪問屬性文件。我該如何解決?

+0

什麼是你的應用程序結構?jsp和properties文件位於何處? –

+0

文件是否在你項目的'/ src'文件夾下? –

回答

29

在你的包創建test.properties文件

pname=xyz 
psurname=abc 

創建JSP文件:

<%@ page language="java" import="java.util.*" %> 
<%@ page import = "java.util.ResourceBundle" %> 
<% ResourceBundle resource = ResourceBundle.getBundle("test"); 
    String name=resource.getString("pname"); 
    String surname=resource.getString("psurname"); %> 
    <%=name %> 
<%=surname%> 
+0

,我需要將屬性文件放在我的包中? –

+0

通常您必須在此處放置屬性文件(位於名爲「classes」的文件夾中):WEB-INF - > classess – Optio

4

JSP在servlet容器中運行,所以它的當前工作目錄是由容器定義的。通常它是安裝容器的目錄或其目錄bin。無論如何,這不是您想要存儲自定義屬性文件的地方。

有兩種典型的方法可以滿足您的需求。

如果您的文件是您的應用程序的一部分,並且在部署時從不改變它,則第一種方法很好。在這種情況下從資源閱讀:

props.load(getClass().getResourceAsStream())

甚至更​​好

props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream())

,如果你想改變你的屬性上部署環境文件中的第二種方法是很好的。在這種情況下,將它放在容器外的文件系統中的某個位置。例如在Linux上或您喜歡的任何其他位置使用/opt/mycompany/conf/myproperties.properties。現在,您應該在創建FileInputStream時使用絕對路徑。

爲了使系統更好地配置,您不應該在代碼中寫入配置文件的路徑。更好的方法是使用系統屬性將它傳遞給應用程序,例如 在運行應用程序服務器時添加參數-Dmycompany.conf=/opt/mycompany/myprops.properties。 當你想讀取的文件執行以下操作:

new FileInputStream(System.getProperties("mycompany.conf"))

您的系統的配置現在可以通過部署獨立控制。

0

嘗試改變FileInputStream fis = new FileInputStream("myproperties.properties");FileInputStream fis = new FileInputStream(new File("myproperties.properties"));

此外,請確保您使用的是類已經在你的JSP文件中導入。 也就是說,

<%@ page import="java.io.FileInputStream" %> 
<%@ page import="java.io.File" %> 
+1

是的,我已正確導入包。 –

+0

是Russell Gutierrez 我已經嘗試過各種文件夾庫,src, –

相關問題