欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Spring boot+beetl+i18n国际化处理的方法

时间:2021-08-15 09:34:30|栏目:JAVA代码|点击:

国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式。它要求从产品中抽离所有地域语言,国家/地区和文化相关的元素。换言之,应用程序的功能和代码设计考虑在不同地区运行的需要,其代码简化了不同本地版本的生产。开发这样的程序的过程,就称为国际化。

Spring boot 搭配慢慢开始火起来的 beetl 模板 配置国际化

首先需要添加WebMvcConfigurer配置

 /**
  * 设置拦截器
  */
 @Override
 public void addInterceptors(InterceptorRegistry registry) {
  registry.addInterceptor(localeChangeInterceptor());
 }
 
 /**
  * 国际化切换拦截器
  * 
  * @return 国际化切换拦截器
  */
 @Bean
 public LocaleChangeInterceptor localeChangeInterceptor() {
  LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
  interceptor.setParamName("lang");
  return interceptor;
 }

 /**
  * 国际化处理器
  * 
  * @return 国际化处理器
  */
 @Bean
 public LocaleResolver localeResolver() {
  SessionLocaleResolver slr = new SessionLocaleResolver();
  //设置默认区域,
  slr.setDefaultLocale(Locale.CHINA);
  return slr;
 }

然后自定义配置beetl

...
 @Autowired
 private WebApplicationContext wac;

 @Bean
 public BeetlTemplateCustomize beetlTemplateCustomize() {
  return new BeetlTemplateCustomize() {
   public void customize(GroupTemplate groupTemplate) {
    // 注册全局共享变量
    Map<String, Object> sharedVars = new HashMap<String, Object>();
    groupTemplate.setSharedVars(sharedVars);

    // 注册国家化函数
    groupTemplate.registerFunction("i18n", new I18nFunction(wac));
   }
  };
 }

然后配置i18n国际化函数

public class I18nFunction implements Function {

 private WebApplicationContext wac;

 public I18nFunction(WebApplicationContext wac) {
  this.wac = wac;
 }

 @Override
 public Object call(Object[] obj, Context context) {
  HttpServletRequest request = (HttpServletRequest) context.getGlobal(WebVariable.REQUEST);
  RequestContext requestContext = new RequestContext(request);
  String message = requestContext.getMessage((String) obj[0]);
  return message;
 }

}

最后配置资源文件

这个资源文件路径也是配出来的,不多介绍了......

测试:

在模板中添加${i18n('messageCode')} , 在url参数中添加lang=en 或者 lang=zh-CN

上一篇:实例解析Java关于static的作用

栏    目:JAVA代码

下一篇:Intellij IDEA 关闭和开启自动更新的提示?

本文标题:Spring boot+beetl+i18n国际化处理的方法

本文地址:http://www.codeinn.net/misctech/167064.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有