使用freemarker手动实现i18n

FTL中的调用效果

1
2
<@message "app.name"/>
<@message "app.name" local="zh_CN"/>

宏定义

1
2
3
4
5
6
7
<#macro message code local="">
<#if local!="">
${i18n("msg", code, local)}
<#else>
${i18n("msg", code, '${springMacroRequestContext.getLocale().language}_${springMacroRequestContext.getLocale().country}')}
</#if>
</#macro>

标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.kangyonggan.demo.freemarker;

import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
* @author kangyonggan
* @since 2018/12/13
*/
@Component
@Log4j2
public class I18nTag extends AbstractFunctionTag {

private static Map<String, Properties> data = new HashMap<>();

/**
* 国际化
*
* @param arguments 参数
* @return 返回UUID
*/
public String msg(List arguments) throws IOException {
if (!hasLessThreeArgs(arguments)) {
throw new RuntimeException("国际化时没有指定参数");
}
String code = arguments.get(1).toString();
String local = arguments.get(2).toString();

Properties properties = getProperties(local);
return properties.getProperty(code);
}

private Properties getProperties(String local) throws IOException {
Properties properties = data.get(local);

if (properties == null) {
properties = loadProperties(local);
data.put(local, properties);
}

return properties;
}

private Properties loadProperties(String local) throws IOException {
Properties properties = new Properties();
InputStream inputStream;
try {
inputStream = this.getClass().getResourceAsStream("/messages_" + local + ".properties");
} catch (Exception e) {
inputStream = null;
}

if (inputStream == null) {
log.info("没有{}的国际化文件,使用默认的", local);
inputStream = this.getClass().getResourceAsStream("/messages.properties");
}

InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
properties.load(reader);
return properties;
}

}

properties文件

messages.properties

1
app.name=dfjz

messages_zh_CN.properties

1
app.name=东方骄子