Welcome 微信登录

首页 / 软件开发 / JAVA / Struts源码研究 - Bean-Message标签篇

Struts源码研究 - Bean-Message标签篇2011-08-18Struts中非常常用的有这样的一个标签:

<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);
}
}
}