我有一个Gradle kts的 spring 启动项目,我正在使用独立的Freemarker库implementation("org.freemarker:freemarker:2.3.32")
作为前端的文本模板.
我编写了以下代码:
Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
cfg.setDirectoryForTemplateLoading(new ClassPathResource("templates").getFile());
cfg.setDefaultEncoding("utf-8");
cfg.setOutputEncoding("utf-8");
Template template = cfg.getTemplate("template.ftl");
System.out.println("template=" + template);
Map<String, Object> data = new HashMap<>();
data.put("vehicles", List.of(new Vehicle("auto", 60), new Vehicle("koloběžka", 5)));
StringWriter stringWriter = new StringWriter();
template.process(data, stringWriter);
String result = stringWriter.toString();
System.out.println(result);
模板文件template.ftl
包含(用于测试目的):
jůůů
我传递给模板的数据("koloběžka")和模板本身("jůůů")都包含捷克语字符.
Problem
模板文件的编码是utf-8
(至少我在Intelligence j中看到的是这样).
如果我没有在Configuration
对象上设置默认编码,它将使用我的语言环境中的编码(我猜),也就是"windows-1250
".然后正确打印模板(template=
行)(变音符号).
但是,如果我将默认编码显式设置为utf-8
,则该行打印j���
.
Question
这怎么可能?
我假设如果模板和Configuration
都使用utf-8
,那么变音符号应该是正确的红色.
另一种方式也困扰着我--Configuration
对象默认使用的编码windows-1250
怎么可能能够很好地从utf-8
编码文件中读取变音符号呢?