Spring boot + beetl + i18n国际化处理

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理