JFinal 國際化 簡單實現 beetl

JFinal自身帶有國際化類com.jfinal.i18n.I18N

文檔裏沒有實現的方法,本身實現了一下,在這裏分享給你們,哪裏有改進的地方請@eyelee

一、編寫properties資源文件 java

yourfilename_zh_CN.properties     test=您好
yourfilename_en_US.properties     test=hello
二、在JFinal配置類,配置常量中
public void configConstant(Constants me) {

	...
	
		//後面兩個參數根據本身狀況添加默認語言國家
		I18N.init("youfilename", null, null);
	
	...

	}
若是資源文件不在classpath下面那麼須要加上包名稱,例如 I18N.init("i18n.youfilename", null, null);


三、在頁面或者類中調用


頁面中調用I18N.getText("key");
在controller建議使用Controller.getText("key");


四、作到這裏並不能實現根據用戶所用的語言對應顯示,這是由於尚未實現自動切換,咱們能夠經過配置一個攔截器實現
定義一個全局過濾器GlobalInterceptor,並在JFinal配置

/***
 * 
 * @author yinjun622 2013-05-25
 */
public class GlobalInterceptor implements Interceptor {

	@Override
	public void intercept(ActionInvocation ai) {
		Controller c = ai.getController();
		String tmp = c.getCookie(Const.I18N_LOCALE);
		String i18n = c.getRequest().getLocale().toString();
		if (!i18n.equals(tmp)) {
			ai.getController().setCookie(Const.I18N_LOCALE, i18n,
					Const.DEFAULT_I18N_MAX_AGE_OF_COOKIE);
		}
		ai.invoke();

	}

}
這樣咱們會在用戶的cookie中記錄所用語言信息當Controller.getText("key");自動去cookie中查找語言並顯示。

咱們還能夠直接使用I18N.getText("key",locale); cookie

五、讓beetl實現國際化 ide

    beetl配置到JFinal在這裏就很少說了,beetl自定義一個函數I18n, 函數

    並配置 gt.registerFunction("i18n", new I18n()); spa

public class I18n implements Function {

	@Override
	public Object call(Object[] obj, Context context) {
		
		HttpServletRequest req = (HttpServletRequest )context.getVar("request");
		return I18N.getText((String) obj[0],req.getLocale());
	}

}

在頁面調用 .net

${i18n("test")}
JFinal國際化的實現,簡單的介紹到這裏,你們能夠提出本身想法與實現,謝謝!
相關文章
相關標籤/搜索