其實這個I18nInterceptor很簡單,而且實際應用中根據實際需求需要進行變通,所以這個I18nInterceptor并不是很實用,當然還是提供了一定的參考作用的.
首先我們來看一下如何使用這個攔截器.
首先我們需要有一個Action,為了演示,其實最簡單的Action就可以,例如
public class I18nIcAction extends ActionSupport
{
public String execute()
{
return SUCCESS;
}
}
展示的頁面例子如下:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="webwork" prefix="ww" %>
<html>
<head>
<title>Test I18n Interceptor</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
Choose: <a href="?locale=en">English Page</a> ,
<a href="?locale=zh_CN">Chinese Page</a>
<br><br>
Content:<ww:text name="desc"/>
</body>
</html>
其中我們使用"locale"作為locale的參數名,頁面里面有2個選項:英文和中文.
對應的資源文件有2個(或者3個,如果包括缺省一個的話):
英文的I18nIcAction_en.properties內容為:
desc=english
中文的I18nIcAction_zh_CN.properties內容為:
desc=\u7b80\u4f53\u4e2d\u6587
接下來我們在xwork.xml里面定義我們的action和攔截器:
<package name="i18nic" extends="webwork-default" namespace="/i18nic">
<interceptors>
<interceptor name="i18n" class="com.opensymphony.xwork.interceptor.I18nInterceptor">
<param name="parameterName">locale</param>
<param name="attributeName">ww_locale</param>
</interceptor>
<interceptor-stack name="i18nStack">
<interceptor-ref name="i18n"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="i18nStack"/>
<action name="index" class="com.jscud.ww2test.i18nic.I18nIcAction">
<result name="success" type="dispatcher">
<param name="location">/i18nic/index.jsp</param>
</result>
</action>
</package>
所有的工作都好了,發布并運行訪問 /i18nic/index.action,一切和預想的一樣.
通過查看I18nInterceptor的源碼,我們可以看到這個攔截器的工作原理是這樣的:
- 如果參數中指定了locale,那么攔截器分析參數,并把locale保存到session中.
- 在后面的action中,攔截器從session中獲取這個locale,并設置action的locale,從而保持用戶的設置.
- 在后續頁面還可以繼續切換locale.
從源碼分析結果來看,這樣做也會有一些實際的問題:
- session過期后,用戶不知道發生了什么,系統使用缺省的locale.
- 只能影響通過action操作的頁面
在實際使用中,我們也要考慮如何解決后面2個問題,例如通過cookie,或者把用戶的配置保存在數據庫里等,這些實現就要結合實際代碼進行實現了,完全可以不需要這個I18nInterceptor就可以實現,當然也很簡單.
各取所需,看自己的實際需要吧 :)
除經特別注明外,本文章版權歸JScud Develop團隊或其原作者所有.
轉載請注明作者和來源. scud(飛云小俠) 歡迎訪問 JScud Develop