简体   繁体   English

使用JTwig模板的Spring webapp中的UTF-8编码问题

[英]UTF-8 encoding issue in Spring webapp with JTwig templates

We're using JTwig templating engine in our Spring webapp. 我们在Spring webapp中使用JTwig模板引擎。 It's great tool and has really nice features, but we have hit a wall with unicode content encoding using UTF-8. 它是一个很好的工具,并且具有非常好的功能,但是我们使用UTF-8打了一个带有unicode内容编码的墙。

First of all, ViewResolver is configured in Java with: 首先, ViewResolver在Java中配置为:

@Bean
public ViewResolver viewResolver() {
    JtwigViewResolver view = new JtwigViewResolver()
    view.setPrefix("/WEB-INF/templates/");
    view.setSuffix(".twig");
    return view;
}

then we have Spring MVC controller adding some text to model and passing it to view: 然后我们让Spring MVC控制器添加一些文本来建模并将其传递给视图:

@RequestMapping(value = "/unicode", produces  = "text/html;charset=UTF-8")
public String testUnicode(ModelMap model) {
    model.addAttribute("text", "tête de bou  간편한 설치 및 사용");
    return "testPage";
}

where it's finally rendered: 它最终呈现的位置:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>
<body>
    <h1>tête de bouton -- 간편한 설치 및 사용</h1>
    From model: {{ text }}
</body>
</html>

but the output is actually: 但输出实际上是:

tête de bouton -- 간편한 설 ? têtedebouton - 간편한설 ? 및 사용 및사용

From model: t?te de bou ??? 从型号:t?te de bou ??? ?? ?? ? ?? ??

Unicode text hardcoded in template i almost right, but the one from model is totally screwed. 在模板中硬编码的Unicode文本我几乎是正确的,但是模型中的那个完全搞砸了。 Any ideas? 有任何想法吗?

Jtwig uses Java's default charset when rendering. Jtwig在渲染时使用Java的默认字符集。 This violates Twig compatibility, as Twig defaults to UTF-8 . 这违反了Twig兼容性,因为Twig默认为UTF-8

I wrote a patch for the issue which was released in 3.1.0. 我为3.1.0中发布的问题写了一个补丁

You can do the following: 您可以执行以下操作:

1) view.setEncoding("UTF-8"); 1) view.setEncoding("UTF-8"); 2) view.setContentType("text/html; charset=UTF-8"); 2) view.setContentType("text/html; charset=UTF-8");

The second 第二

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM