Structs2 request_locale國際化介紹,structs1structs2

來源:互聯網
上載者:User

Structs2 request_locale國際化介紹,structs1structs2

眾所周知,struts2中使用了大量的攔截器(即是傳說中的interceptor),其中國際化使用的攔截器為com.opensymphony.xwork2.interceptor.I18nInterceptor,那麼接下來分析一下I18nInterceptor這個類。

一.屬性

  I18nInterceptor有三個屬性,分別為parameterName,requestOnlyParameterName,attributeName。

  parameterName:http request請求中的參數名字,該參數反映了應該轉向的locale,並且儲存在session中,所以會話過程都有效。預設為request_locale。

  requestOnlyParameterName:http request請求中的參數名字,該參數反映了應該轉向的locale,不儲存在session中,所以只對當前請求有效。預設為request_only_locale。

  attributeName:session中儲存使用者選擇的locale值對應的key值。預設值為WW_TRANS_I18N_LOCALE

二.方法

  攔截器中最重要的方法當屬intercept方法,其他方法暫時忽略。該方法的邏輯如下:

  1.擷取parameters對象。Map<String, Object> params = invocation.getInvocationContext().getParameters()

  2.在params在取出並移除request_locale。  Object requested_locale = params.remove(parameterName);(parameters對象擷取參數得到的是一個字串數組)

      2.1 requested_locale不為null,是Array,長度為1,取出requested_locale的值。否則,2.2

      2.2 返回requested_locale

  3.在step2中擷取到的request_locale如果為空白,則將2中的parameterName換成requestOnlyParameterName,執行step2,返回requested_locale

  4.如果通過step2和step3擷取到的requested_locale不為null,則將requested_locale轉換成locale並儲存在session中(注意:如果擷取到的requested_locale.toString()為null或Null 字元串或者"_",此時locale=Locale.getDefault())。

  5.如果通過step2和step3擷取到的requested_locale為null,則判斷session中key=attributeName的value值是否存在,若存在則locale=session.get(attributeName),否則locale = invocation.getInvocationContext().getLocale()(此處意思是沒有找到重寫的locale定義,則保持當前的invocation locale,即使用者在瀏覽器中設定的語言)。

  至此,通過I18nInterceptor得到了locale,此後的處理就不言而喻了,肯定就是根據locale取值了。

 可以看出:使用者在畫面設定的locale優先順序高於瀏覽器設定語言得到的locale。

可以看到此處超連結處設定request_locale=en_US,這樣struts2擷取到的locale當然就是en_US,此時不管瀏覽器語言設定成什麼,畫面顯示的都是英文的資源,並且在會話期間都有效。若設定的是request_only_locale=en_US,這樣只是在當前請求下會顯示英文介面,重新整理頁面就會顯示中文了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.