歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Struts2 request_locale國際化介紹

Struts2 request_locale國際化介紹

日期:2017/3/1 9:36:12   编辑:Linux編程

眾所周知,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或空字符串或者"_",此時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,這樣只是在當前請求下會顯示英文界面,刷新頁面就會顯示中文了。

struts2文件上傳(保存為BLOB格式) http://www.linuxidc.com/Linux/2014-06/102905.htm

Struts2的入門實例 http://www.linuxidc.com/Linux/2013-05/84618.htm

Struts2實現ModelDriven接口 http://www.linuxidc.com/Linux/2014-04/99466.htm

遇到的Struts2文件下載亂碼問題 http://www.linuxidc.com/Linux/2014-03/98990.htm

Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm

Struts2 注解模式的幾個知識點 http://www.linuxidc.com/Linux/2013-06/85830.htm

Struts 的詳細介紹:請點這裡
Struts 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved