Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add Freemarker support to a Spring MVC webapp? Dependency issue?

I'm trying to create a Spring MVC application using Freemarker and Java configuration.

I'm used to using JSPs, but thought I'd give Freemarker a spin in this project.

I've added Freemarker as a dependancy and the jar is being downloaded by Maven:

        <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.20</version>
    </dependency>

I'm trying to use 3.2.3.RELEASE version of Spring.

My MVC configuration, assembled from reading similar question:

@ComponentScan(basePackages="yhj.*")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{


@Bean
public ViewResolver viewResolver() {
    FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
    resolver.setCache(true);
    resolver.setPrefix("");
    resolver.setSuffix(".ftl");
    return resolver;

}

@Bean
public FreeMarkerConfigurer freemarkerConfig() {
    FreeMarkerConfigurer result = new FreeMarkerConfigurer();
    result.setTemplateLoaderPath("/WEB-INF/views/");
    return result;

}
}

When I try run this up I get a compilation error, my IDE is telling me the method 'setTemplateLoaderPath(String)' cannot be resolved.

So... does look like the right way of going about configuring Spring MVC with Freemarker? What dependency do I need to add to my POM if that is the issue?

like image 331
DaFoot Avatar asked Jul 13 '13 11:07

DaFoot


1 Answers

My solution for Spring Boot 1.0.2, Spring 4.0.3, and FreeMarker 2.3.20 was the following class:

@Configuration
public class MvcConfigurer extends WebMvcConfigurerAdapter {
  @Bean
  public ViewResolver viewResolver() {
    FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
    resolver.setCache(true);
    resolver.setPrefix("");
    resolver.setSuffix(".ftl");
    resolver.setContentType("text/html; charset=UTF-8");
    return resolver;
  }

  @Bean
  public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {
    FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory();
    factory.setTemplateLoaderPath("classpath:templates");
    factory.setDefaultEncoding("UTF-8");
    FreeMarkerConfigurer result = new FreeMarkerConfigurer();
    result.setConfiguration(factory.createConfiguration());
    return result;
  }
}

In addition you need the same pom.xml changes as in the question and DaFoot's own answer.

like image 200
Samuli Pahaoja Avatar answered Oct 12 '22 10:10

Samuli Pahaoja