Struts中非常常用的有這樣的一個標籤:
<bean:message key="welcome.title"/>
眾所周知,這個標籤做的事情是這樣的:
訪問在struts-config.xml中定義的資源檔,一般是application.properties,一般是這樣定義的:
<message-resources parameter="resources.application"/>
根據以上的定義,Struts將到WEB-INF/classes/resource/下去找application.properties檔案,這是從以上配置資訊的表面上看起來是這樣,但通過查看Struts的源碼,可以看到如下的代碼:在org.apache.struts.util.PropertyMessageResources類中,有如下的代碼:
通過這段代碼,可以看到
A、.properties副檔名是寫死在代碼中的,所以資源檔必須使用這個副檔名
B、Struts並不是單純去尋找application.properties檔案,而是首先找到application,賦給name變數然後加上底線"_",然後再加上localeKey(如zh,en),然後再加上.properties
C、確定了檔案名稱之後,Struts使用了ClassLoader類的getResourceAsStream方法得到了一個InputStream
D、然後Struts使用了java.util.Properties類的load方法,將資源檔中的所有資源讀出放到了一個HashMap裡面
E、然後Struts就可以根據key值取出不同的message給前台了
// Set up to load the property resource for this locale key, if we can
String name = config.replace('.', '/');
if (localeKey.length() > 0) {
name += "_" + localeKey;
}
name += ".properties";
InputStream is = null;
Properties props = new Properties();
// Load the specified property resource
if (log.isTraceEnabled()) {
log.trace(" Loading resource '" + name + "'");
}
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = this.getClass().getClassLoader();
}
is = classLoader.getResourceAsStream(name);
if (is != null) {
try {
props.load(is);
} catch (IOException e) {
log.error("loadLocale()", e);
} finally {
try {
is.close();
} catch (IOException e) {
log.error("loadLocale()", e);
}
}
}