首页 > 解决方案 > Freemarker 与 SparkJava 的集成产生了意外的 unicode 字符串输出

问题描述

我正在使用 freemarker 集成在 SparkJava 中构建应用程序。

我正在尝试渲染一个 freemarker 模板(实际上不包含任何变量):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>hello</p>
</body>
</html>

在我的控制器中,我有以下配置:

final Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
configuration.setDirectoryForTemplateLoading(new File(contextClassLoader.getResource("www/public").toURI()));
configuration.setDefaultEncoding("UTF-8");
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
configuration.setLogTemplateExceptions(false);
return new FreeMarkerEngine(configuration).render(new ModelAndView(Collections.singletonMap("",""), "index.ftl"));

但是浏览器中的结果输出如下:

"\u003c!DOCTYPE html\u003e\n\u003chtml lang\u003d\"en\"\u003e\n\u003chead\u003e\n \u003cmeta charset\u003d\"UTF-8\"\u003e\n \u003ctitle\u003eTitle \u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n\u003cp\u003ehello\u003c/p\u003e\n\u003c/body\u003e\n\u003c/html\u003e"

我做错了什么,如何正确呈现页面?

标签: javatemplatesrenderfreemarkerspark-java

解决方案


答案很简单:在这种情况下,路由语句如下所示:

get("/hello", aMethodToRenderPage, gson::toJson);

其中调用toJson指的是下面的方法

@Override
public String render(Object model) {
    return gson.toJson(model);
}

在 ResponseTransformer 中定义。通过将字符转换为 Unicode 表示,将响应转换为 JSON 字符串。 要获得所需的输出(带有填充变量的 HTML),请删除此类调用,使其看起来像:

get("/hello", aMethodToRenderPage);

推荐阅读