I have a problem with configuration freemarker in spring boot. I have next code in my application class.
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer freemarkerConfig = new FreeMarkerConfigurer();
freemarkerConfig.setTemplateLoaderPath("template");
freemarkerConfig.setDefaultEncoding("UTF-8");
Map<String, Object> freemarkerVariables = new HashMap<String, Object>();
freemarkerVariables.put("layout", freemarkerLayoutDirectives());
freemarkerConfig.setFreemarkerVariables(freemarkerVariables);
return freemarkerConfig;
}
@Bean
public ViewResolver viewResolver() {
FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
viewResolver.setCache(false);
viewResolver.setPrefix("");
viewResolver.setSuffix(".ftl");
viewResolver.setContentType("text/html; charset=utf-8");
return viewResolver;
}
@Bean
public Map<String, TemplateModel> freemarkerLayoutDirectives() {
Map<String, TemplateModel> freemarkerLayoutDirectives = new HashMap<String, TemplateModel>();
freemarkerLayoutDirectives.put("extends", new ExtendsDirective());
freemarkerLayoutDirectives.put("block", new BlockDirective());
freemarkerLayoutDirectives.put("put", new PutDirective());
return freemarkerLayoutDirectives;
}
I use this code for configurate freemarker and freemarkerLayoutDirectives (inheratance)
My templates placed in
src/main/webapp/templates
When i build and run app in my local machine all work nice, but when i try to to run same .jar on linux server or in Docker(oficial spring docker) my app crashed when try render view wit next eror:
There was an unexpected error (type=Not Found, status=404).
No message available
My controller code
@RequestMapping(path = "/", method = {RequestMethod.GET})
public String homePage(Model model) String name,
BindingResult errors
) {
return "index";
}
You need to make sure that the FreemarkerConfigurer knows where your template location is. First, I see you called the method "setTemplateLoaderPath("template")", however, the folder is called "templates" (plural).
Second, I think that folder path is relative to where your program runs from (aka the working directory), which can change from an IDE to another. Your best option is to place your templates inside the resources folder. That way they are packaged in the Jar, and they can then be referenced as classpath resources, regardless of where you run your program (as an executable JAR, a docker image or through the IDE).
You can check this article for an example of setting up the freemarkerconfigurer https://nullbeans.com/spring-boot-freemarker-configuration-example/