Search code examples
javatemplatesrenderfreemarkerspark-java

Freemarker integration with SparkJava produces unexpected unicode string output


I am building an application in SparkJava with freemarker integration.

I am trying to render a freemarker template (actually containing no vars):

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

In my controller I have the following configuration:

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"));

But the result output in the browser is the following:

"\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"

What am I doing wrong and how can I render the page correctly?


Solution

  • The answer is trivial: in such situation the route statement looked like the following:

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

    Where the call toJson refers to the following method

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

    defined in a ResponseTransformer. That transforms the response into JSON String by turning chars into unicode representation. To get the desired output (HTML with filled in vars), remove such call, so that it looks like:

    get("/hello", aMethodToRenderPage);