Solon Web 开发,十一、国际化

1、添加国际化配置

resources/i18n/messages.properties

login.title=登录
login.name=世界

resources/i18n/messages_en_US.properties

login.title=Login
login.name=world

2、 使用 solon.i18n 插件

  • 使用国际化工具类,获取默认消息
@Controller
public class DemoController {
    @Mapping("/demo/")
    public String demo(Context ctx) {
        return I18nUtil.getMessage(ctx, "login.title");
    }
}
  • 使用注解,为视图模板提供支持
@I18n("i18n.login")
@Controller
public class LoginController {
    @Mapping("/login/")
    public ModelAndView login() {
        return new ModelAndView("login.ftl");
    }
}

在各种模板里的使用方式:

beetl::

i18n::${i18n["login.title"]}
i18n::${@i18n.get("login.title")}
i18n::${@i18n.getAndFormat("login.title",12,"a")}

enjoy::

i18n::#(i18n.get("login.title"))
i18n::#(i18n.getAndFormat("login.title",12,"a"))

freemarker::

i18n::${i18n["login.title"]}
i18n::${i18n.get("login.title")}
i18n::${i18n.getAndFormat("login.title",12,"a")}

thymeleaf::

i18n::<span th:text='${i18n.get("login.title")}'></span>
i18n::<span th:text='${i18n.getAndFormat("login.title",12,"a")}'></span>

velocity::

i18n::${i18n["login.title"]}
i18n::${i18n.get("login.title")}
i18n::${i18n.getAndFormat("login.title",12,"a")}

3、 也支持分布式国际化本置

这个方式,适合对接企业内部的国际化配置中台。

//实现一个国际化内容块的工帮
public class I18nBundleFactoryImpl implements I18nBundleFactory {
    @Override
    public I18nBundle create(String bundleName, Locale locale) {
        if (I18nUtil.getMessageBundleName().equals(bundleName)) {
            bundleName = Solon.cfg().appName();
        }

        return new I18nBundleImpl(I18nContextManager.getMessageContext(bundleName), locale);
    }
}

//然后注册到Bean容器
Aop.wrapAndPut(I18nBundleFactory.class, new I18nBundleFactoryImpl());
posted @ 2022-01-19 08:18  带刺的坐椅  阅读(98)  评论(0编辑  收藏  举报