JFinal 的國際化不需要自己發明輪子,只要註冊一個全域攔截器 I18nInterceptor,剩下的語言判定、Cookie 記憶、資源載入都由它代勞。
public class MppConfig extends JFinalConfig {
/** 配置全域攔截器 */
public void configInterceptor(Interceptors me) {
me.add(new I18nInterceptor());
}
}
之後每個 action 請求都會先被攔截,進入 intercept 方法。
public class I18nInterceptor implements Interceptor {
private String localeParaName = "_locale";
private String resName = "_res";
private boolean isSwitchView = false;
public I18nInterceptor() {}
public I18nInterceptor(String localeParaName, String resName) {
if (StrKit.isBlank(localeParaName))
throw new IllegalArgumentException("localeParaName can not be blank.");
if (StrKit.isBlank(resName))
throw new IllegalArgumentException("resName can not be blank.");
this.localeParaName = localeParaName;
this.resName = resName;
}
public I18nInterceptor(String localeParaName, String resName, boolean isSwitchView) {
this(localeParaName, resName);
this.isSwitchView = isSwitchView;
}
/** i18n 資源檔的 baseName */
protected String getBaseName() {
return I18n.defaultBaseName;
}
/**
* 1: 請求參數帶 locale 時,採用它並寫入 cookie
* 2: 否則讀 cookie 中的 locale
* 3: 都沒有就用預設 locale
* 4: 以 setAttr(resName, resObject) 把 Res 傳給視圖
*/
public void intercept(Invocation inv) {
Controller c = inv.getController();
String localeParaName = getLocaleParaName();
String locale = c.getPara(localeParaName);
if (StrKit.notBlank(locale)) { // 切換語言並記住選擇
c.setCookie(localeParaName, locale, Const.DEFAULT_I18N_MAX_AGE_OF_COOKIE);
} else { // 讀 cookie,讀不到就退回預設
locale = c.getCookie(localeParaName);
if (StrKit.isBlank(locale))
locale = I18n.defaultLocale;
}
if (isSwitchView) {
switchView(locale, c);
} else {
Res res = I18n.use(getBaseName(), locale);
c.setAttr(getResName(), res);
}
inv.invoke();
}
/**
* 有些系統需要國際化的文案太多,連 CSS 與 HTML 結構都不同,
* 這時直接準備多套同名視圖,以 locale 作為子目錄分類存放,
* 由本攔截器動態切換視圖即可,不必逐字替換。
*/
public void switchView(String locale, Controller c) {
Render render = c.getRender();
if (render != null) {
String view = render.getView();
if (view != null) {
if (view.startsWith("/"))
view = "/" + locale + view;
else
view = locale + "/" + view;
render.setView(view);
}
}
}
}
關鍵在最後兩段邏輯:locale 決定用哪一份資源,baseName 固定為 i18n,兩者拼接就是資源檔名,接著實例化 Res 並塞進視圖。
controller.setAttr("_res", res);
i18n_zh_CN.properties:
msg=\u4F60\u597D{0}, \u4ECA\u5929\u662F{1}
i18n_en_US.properties:
msg=Hello {0}, today is {1}.
不同地區對應不同 locale,例如中國大陸是 zh_CN、香港是 zh_HK、美國是 en_US,因此只要補齊對應的資源檔即可。
以 Freemarker 為例:
${_res.msg!}
整體流程可以概括為:攔截請求 → 決定 locale(參數 > Cookie > 預設)→ 載入 Res 或切換視圖 → 放行後續攔截器與 Controller。若你的頁面差異大到幾乎是兩個不同頁面,直接開 isSwitchView 走多套視圖,會比逐句國際化省事得多。