我希望通過jsp在HTML/XML中顯示屬性。如:java.util.properties的Getters/Setters
${MyClass.properties.propertieOne}
我創建了屬性MProperties的擴展類,但是如何在該類中爲我的屬性創建getter?
BR Kolesar
我希望通過jsp在HTML/XML中顯示屬性。如:java.util.properties的Getters/Setters
${MyClass.properties.propertieOne}
我創建了屬性MProperties的擴展類,但是如何在該類中爲我的屬性創建getter?
BR Kolesar
您可以創建類來處理與構造你的屬性,如
private Properties props = null;
private MyProperties() throws IOException {
FileInputStream propFile = new FileInputStream(FULL_PATH);
props = new Properties(System.getProperties());
props.load(propFile);
RegistryManager rm = RegistryManager.singleton();
rm.addRegistry("MyProperty", this);
}
public static MyProperties Singelton() {
synchronized (MyProperties.class) {
if (theInstance == null) {
try {
theInstance = new MyProperties();
} catch (IOException e) {
throw new MissingResourceException("Unable to load property file \"" + FULL_PATH + "\"", MyProperties.class.getName(),
PROPERTIES_FILENAME);
}
}
}
return theInstance;
}
和不是像
public static String getProperty(String propertyName) {
String value = Singelton().props.getProperty(propertyName);
if (value == null) {
LOGGER.warning("propertyName (" + propertyName + ") not found in property file (" + FULL_PATH + ")");
}
return value;
}
終於在代碼通過一個方法獲取屬性則只能撥打
String desiredProperty = MyProperties.getProperty("propertyKey");
一些代碼丟失,有些你可能不需要,但你應該明白,如果這是你想要做的...
可以在Properties
類使用store(Writer writer, String comments)
方法。將你的屬性寫入一個StringWriter並使用它的String來在HTML上打印。
${yourObject.properties.propertyOne}
的作品。 Properties extends Hashtable implement Map
和${map.key}
爲您提供該密鑰下的值。但是你不應該使用JSP中的setter,所以這只是爲了顯示目的。
但是,您無法直接從靜態字段訪問它。您必須將其添加到某個上下文 - 請求或應用程序。例如,在一個ServletContextListener.contextInitialized(..)
:
servletContext.addAttribute("yourProperties", MyClass.properties);
(那麼你必須映射在web.xml中<listener>
,當然)
如果擴展Properties
,你可能知道正是你想要的字段有。在這種情況下,只用一個POJO(簡單對象)創建一個POJO(簡單對象)似乎更好一些,它包含這些字段和適當的getter(以及你想要的setter和/或構造函數)。如果您不知何故需要Properties
的動態性(?),請忽略此答案。
通常.properties文件被表示爲一張地圖,所以你需要爲地圖鍵提供getter並在表達式中使用它們。 AFAIK'$ {...}'是隻讀的,所以在這裏你不需要特殊的setter。 – Thomas