生成的HTML显示?而不是国际字符

时间:2016-10-05 06:33:49

标签: java encoding freemarker

我的项目中存在以下问题:

如果我在本地(以及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文件(在本地运行时)。但是当我在云端运行时,它会显示?

关于我做错什么的任何想法?

1 个答案:

答案 0 :(得分:3)

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

此:

OutputStreamWriter out = new OutputStreamWriter(outputStream);

应该是这样的:

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

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

相关问题