Friday 26 October 2012

Spring FreeMarker Integration Example (With Annotations)

This post provides a simple example of FreeMarker integration within a Spring application. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-FreeMarker-Integration directory.

FreeMarker also offers two great tutorials: the Template Author's Guide and the Programmer's Guide.

Configuration

We need to modify our Web configuration to set a FreeMarker viewer and a FreeMarker configurer:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver getViewResolver() {

        FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
        resolver.setCache(false);
        // resolver.setPrefix("");
        resolver.setSuffix(".ftl");

        return resolver;

    }

    @Bean
    public FreeMarkerConfigurer getFreemarkerConfig() {

        FreeMarkerConfigurer result = new FreeMarkerConfigurer();
        result.setTemplateLoaderPath("WEB-INF/pages/");

        return result;

    }

}
Our controller remains very simple:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home(Model model) {

        model.addAttribute("MsTime", System.currentTimeMillis());

        return "Home";

    }

}

FreeMarker Template

We use a simple FreeMarker template:
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring FreeMarker Example !!!</title>
</head>
<body>
    This is the Spring FreeMarker Example !!!

    Time is: ${MsTime}!
</body>
</html>

Maven Dependency

We need the following dependency:
 <dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.19</version>
</dependency>

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8282/spring-freemarker-integration/.

The home page will display:



More Spring related posts here.

3 comments:

  1. Thanks lot, I was looking for this to understand how freeMarker get objects from Controllers.

    ReplyDelete
  2. Why do you include Sitemesh as a dependency in your project? Does Freemarker only work with Sitemesh or are you including it for some other aspect of the project this example came from?

    ReplyDelete
    Replies
    1. I have just checked out the project again, but there is no dependency to Sitemesh in the pom.xml...

      Delete