Springboot+thymeleaf+数据库实现国际化

Springboot+thymeleaf+数据库实现国际化

思路:自定义thymeleaf消息解析器

由官方文档3.1.1可知,外部化文本(语法:#{…})是从模板⽂件中提取模板代码的⽚段,可以实现国际化,而Thymeleaf中外部化⽂本的位置是完全可配置的,它将取决于正在使⽤的具体的org.thymeleaf.messageresolver.IMessageResolver实现,如果想要从数据库获取消息,需要创建⾃⼰的实现

由官方文档15.2可知,Thymeleaf + Spring集成包提供了使⽤标准Spring⽅式检索外部化消息的IMessageResolver实现,通过使⽤Spring应⽤程序上下⽂中声明的MessageSource bean来实现

由此可知,实现org.springframework.context.MessageSource,将实现类注册为“messageSource”,即可实现从数据库或其他数据源获取国际化文本

实现MessageSource

实现MessageSource,发现需要复写三个方法
Springboot+thymeleaf+数据库实现国际化_第1张图片
Springboot+thymeleaf+数据库实现国际化_第2张图片

参数解释:
code: 消息键 
locale: 地区,包含在请求头中
args: 占位符,可以为空
返回值即为替换外部化文本的值

替换的逻辑可以自定义

自定义逻辑从数据库或别的数据源获取文本

Springboot+thymeleaf+数据库实现国际化_第3张图片
在这个类上加@Component注解,值为messageSource,代表覆盖springboot原有的默认配置
在这里插入图片描述

使用外部文本语法

在模板中使用#{…}语法,消息键会被传到getMessage()方法中进行逻辑运算,然后返回一个替换的文本
Springboot+thymeleaf+数据库实现国际化_第4张图片
Springboot+thymeleaf+数据库实现国际化_第5张图片

代码

@Component("messageSource")
public class MyMessageSource implements MessageSource {

	@Override
	public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
		return getI18nMsg(code, locale, args);
	}

	@Override
	public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException {
		return getI18nMsg(code, locale, args);
	}

	@Override
	public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
		return getI18nMsg(resolvable.getCodes()[0], locale, resolvable.getArguments());
	}

	private String getI18nMsg(String code, Locale locale, Object... ags) {
		// 此处未来可以根据code和locale从数据库获取
		if (locale == null) {
			return null;
		} else if (Locale.CHINA.equals(locale)) {
			return code + "国际化文本";
		} else if (Locale.ENGLISH.equals(locale)) {
			return code + "International Text";
		} else {
			return code + "其他语言";
		}
	}
}

你可能感兴趣的:(Springboot+thymeleaf+数据库实现国际化)