生成 html 节目?而不是国际字符

Generated html shows ? instead of international characters

我的项目中遇到以下问题:

如果我 运行 我在本地(和来自 Jar)的项目,我正在处理的 .ftlh 文件编译得很好 - 它显示所有国际字符没有任何问题(比如 ą ę ć).

现在,如果我将我的项目部署到云端,所有这些国际字符都显示为 ?。我不知道发生了什么,因为我在 .ftlh 文件中设置了以下内容:

<#ftl encoding='UTF-8'>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
</head>
<body>

还有我的配置:

@Bean
public freemarker.template.Configuration templateConfiguration() throws IOException {
    freemarker.template.Configuration configuration = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_24);
    configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/folder"));
    configuration.setDefaultEncoding("UTF-8");
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setLogTemplateExceptions(false);
    return configuration;
}

这就是我处理模板的方式:

@Qualifier("templateConfiguration")
@Autowired
private Configuration configuration;


public void generateEmail(Order order, OutputStream outputStream) throws IOException, TemplateException  {
    Template template = configuration.getTemplate(EMAIL, "UTF-8");
    OutputStreamWriter out = new OutputStreamWriter(outputStream);
    template.process(order, out);
}

当我生成电子邮件并在以下内容上使用 System.out.println 时:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try{
    emailsTemplateService.generateEmail(order, byteArrayOutputStream);
} catch (Exception e){
    e.printStackTrace();
}
String htmlMessage =  new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);

System.out.println(htmlMessage);

它将打印带有国际字符的 HTML 文件(在本地 运行s 时)。但是当我在云端运行时,它会显示?

关于我做错了什么有什么想法吗?

你几乎在所有情况下都使用了指定的字符编码,这很好。但是你忘记了一个。

这个:

OutputStreamWriter out = new OutputStreamWriter(outputStream);

应该是这样的:

OutputStreamWriter out = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);

由于您没有指定 OutputStreamWriter 的编码,它采用了平台默认编码,这对于您 运行 代码所在的两个平台是不同的(而且它不是 UTF-8云)