I have a Spring Boot application in which I need to use Freemarker to display HTML pages in a browser.
I am new to Freemarker and I am struggling to display even a simple HTML page, and I do not know why it will not display the page.
My template file is in src/main/resources/templates, and my freemarker config is:
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() throws IOException, TemplateException {
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setTemplateLoaderPath("classpath:/templates");
freeMarkerConfigurer.setDefaultEncoding("UTF-8");
freemarker.template.Configuration configuration = freeMarkerConfigurer.createConfiguration();
configuration.setTagSyntax(freemarker.template.Configuration.SQUARE_BRACKET_TAG_SYNTAX);
configuration.setRecognizeStandardFileExtensions(true);
configuration.setOutputFormat(HTMLOutputFormat.INSTANCE);
freeMarkerConfigurer.setConfiguration(configuration);
return freeMarkerConfigurer;
}
@Bean
public ViewResolver viewResolver() {
FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
viewResolver.setCache(false);
viewResolver.setPrefix("");
viewResolver.setSuffix(".ftlh");
viewResolver.setContentType("text/html; charset=utf-8");
return viewResolver;
}
And my controller is:
@RestController
public class HelloWorldController {
@GetMapping("/hello-world")
public String helloWorld(@ModelAttribute("model") ModelMap model) {
String message = "Hello World!";
model.addAttribute("message", message);
return "hello";
}
}
I am using ftlh file extension for templates and my hello.ftlh file looks like:
[#import "_components.ftlh" as comp]
[@comp.page title="Hello"]
[@comp.hello]${message}[/@comp.hello]
[/@comp.page]
Replace @RestController with @Controller. @Controller is meant for rendering views and allows returning view names that resolve to templates