其實這個I18nInterceptor很簡單,而且實際應(yīng)用中根據(jù)實際需求需要進(jìn)行變通,所以這個I18nInterceptor并不是很實用,當(dāng)然還是提供了一定的參考作用的.
首先我們來看一下如何使用這個攔截器.
首先我們需要有一個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的參數(shù)名,頁面里面有2個選項:英文和中文.
對應(yīng)的資源文件有2個(或者3個,如果包括缺省一個的話):
英文的I18nIcAction_en.properties內(nèi)容為:
desc=english
中文的I18nIcAction_zh_CN.properties內(nèi)容為:
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>
所有的工作都好了,發(fā)布并運(yùn)行訪問 /i18nic/index.action,一切和預(yù)想的一樣.
通過查看I18nInterceptor的源碼,我們可以看到這個攔截器的工作原理是這樣的:
- 如果參數(shù)中指定了locale,那么攔截器分析參數(shù),并把locale保存到session中.
- 在后面的action中,攔截器從session中獲取這個locale,并設(shè)置action的locale,從而保持用戶的設(shè)置.
- 在后續(xù)頁面還可以繼續(xù)切換locale.
從源碼分析結(jié)果來看,這樣做也會有一些實際的問題:
- session過期后,用戶不知道發(fā)生了什么,系統(tǒng)使用缺省的locale.
- 只能影響通過action操作的頁面
在實際使用中,我們也要考慮如何解決后面2個問題,例如通過cookie,或者把用戶的配置保存在數(shù)據(jù)庫里等,這些實現(xiàn)就要結(jié)合實際代碼進(jìn)行實現(xiàn)了,完全可以不需要這個I18nInterceptor就可以實現(xiàn),當(dāng)然也很簡單.
各取所需,看自己的實際需要吧 :)
除經(jīng)特別注明外,本文章版權(quán)歸JScud Develop團(tuán)隊或其原作者所有.
轉(zhuǎn)載請注明作者和來源. scud(飛云小俠) 歡迎訪問 JScud Develop