1 快速上手

2 JFinalConfig

3 Controller

4 AOP

5 ActiveRecord

6 Enjoy 模板引擎

7 EhCachePlugin

8 RedisPlugin

9 Cron4jPlugin

10 Validator

11 国际化

12 Json 转换

13 JFinal架构及扩展

14 升级到 5.1.2

11.3 I18nInterceptor

     I18nInterceptor拦截器是针对于web应用提供的一个国际化组件,以下是在freemarker模板中使用的例子:

//先将I18nInterceptor配置成全局拦截器
public void configInterceptor(Interceptors me) {
  me.add(new I18nInterceptor());
}
 
// 然后在 jfinal 模板引擎中即可通过 _res 对象来获取国际化数据
#(_res.get("msg"))

    以上代码通过配置了I18nInterceptor拦截action请求,然后即可在freemarker模板文件中通过名为_res对象来获取国际化数据,I18nInterceptor的具体工作流程如下:

  • 试图从请求中通过controller.getPara(“_locale”)获取locale参数,如果获取到则将其保存到cookie之中 

  • 如果controller.getPara(“_locale”)没有获取到参数值,则试图通过controller.getCookie(“_locale”)得到locale参数

  • 如果以上两步仍然没有获取到locale参数值,则使用I18n. defaultLocale的值做为locale值来使用

  • 使用前面三步中得到的locale值,通过I18n.use(locale)得到Res对象,并通过controller.setAttr(“_res”, res)将Res对象传递给页面使用

  • 如果I18nInterceptor. isSwitchView为true值的话还会改变render的view值,实现整体模板文件的切换,详情可查看源码。


    以上步骤I18nInterceptor中的变量名”_locale”、”_res”都可以在创建I18nInterceptor对象时进行指定,不指定时将使用默认值。还可以通过继承I18nInterceptor并且覆盖getLocalPara、getResName、getBaseName来定制更加个性化的功能。

    在有些 web 系统中,页面需要国际化的文本过多,并且 css 以及 html 也因为国际化而大不相同,对于这种应用场景先直接制做多套同名称的国际化视图,并将这些视图以 locale 为子目录分类存放,最后使用I18nInterceptor拦截器根据 locale 动态切换视图,而不必对视图中的文本逐个进行国际化切换,只需将I18nInterceptor.isSwitchView设置为true即可,省时省力。