Struts源碼研究

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.