Using FreeMarker Views in Spring MVC

[Last Updated: Sep 20, 2017]

This example demonstrates how to use FreeMarker templates as the view technology in a Spring MVC application.


Maven dependencies



spring-context-support provides support for integrating common third-party libraries into Spring application context which includes template engines (FreeMarker, JasperReports, Velocity).

Java Config class

public class MyWebConfig extends WebMvcConfigurerAdapter {

  public void configureViewResolvers (ViewResolverRegistry registry) {

  public FreeMarkerConfigurer freeMarkerConfigurer() {
      FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
      return configurer;
  • FreeMarkerConfigurer

    This Spring class wraps an instance of freemarker.template.Configuration which is the main entry point into the FreeMarker API.

  • WebMvcConfigurerAdapter#configureViewResolvers

    The method ViewResolverRegistry#freeMarker() registers an instance of FreeMarkerViewResolver as bean. Alternatively, we can register the bean ourselves:
        public ViewResolver freeMarkerViewResolver () {
            FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
            return resolver;

Writing a Spring Controller

public class MyController {
  public String handleRequest (Model model) {
      model.addAttribute("msg", "A message from the controller");
      return "my-page";

The FreeMarker template


<!DOCTYPE html>
<html lang="en">
<h2>FreeMarker View</h3>
	<div> Message: ${msg}</div>
	<div> Time: ${time} </div>

More info about the FreeMarker template engine can be found here.


The generated html:

<!DOCTYPE html>
<html lang="en">
<h2>FreeMarker View</h3>
	<div> Message: A message from the controller</div>
	<div> Time: 22:39:13.512 </div>

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.3.10.RELEASE: Spring Web MVC.
  • spring-context-support 4.3.10.RELEASE: Spring Context Support.
  • freemarker 2.3.26-incubating: FreeMarker is a "template engine"; a generic tool to generate text output based on templates.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

FreeMarker View in Spring MVC Select All Download
  • spring-freemarker-view-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
            • views
              • my-page.ftl

    See Also