简体   繁体   中英

UTF-8 encoding issue in Spring webapp with JTwig templates

We're using JTwig templating engine in our Spring webapp. It's great tool and has really nice features, but we have hit a wall with unicode content encoding using UTF-8.

First of all, ViewResolver is configured in Java with:

@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:

@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 -- 간편한 설 ? 및 사용

From model: t?te de bou ??? ?? ? ??

Unicode text hardcoded in template i almost right, but the one from model is totally screwed. Any ideas?

Jtwig uses Java's default charset when rendering. This violates Twig compatibility, as Twig defaults to UTF-8 .

I wrote a patch for the issue which was released in 3.1.0.

You can do the following:

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

The second

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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