Freemarker 与 SparkJava 的集成产生意外的 unicode 字符串输出
Freemarker integration with SparkJava produces unexpected unicode string output
我正在使用 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"
我做错了什么以及如何正确呈现页面?
答案很简单:在这种情况下,路由语句如下所示:
get("/hello", aMethodToRenderPage, gson::toJson);
其中调用toJson
指的是下面的方法
@Override
public String render(Object model) {
return gson.toJson(model);
}
在 ResponseTransformer 中定义。通过将字符转换为 unicode 表示,将响应转换为 JSON 字符串。
要获得所需的输出(HTML 已填充变量),删除 这样的调用,使其看起来像:
get("/hello", aMethodToRenderPage);
我正在使用 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"
我做错了什么以及如何正确呈现页面?
答案很简单:在这种情况下,路由语句如下所示:
get("/hello", aMethodToRenderPage, gson::toJson);
其中调用toJson
指的是下面的方法
@Override
public String render(Object model) {
return gson.toJson(model);
}
在 ResponseTransformer 中定义。通过将字符转换为 unicode 表示,将响应转换为 JSON 字符串。 要获得所需的输出(HTML 已填充变量),删除 这样的调用,使其看起来像:
get("/hello", aMethodToRenderPage);