Using Groovy Views in Spring MVC

[Last Updated: Sep 20, 2017]

The Groovy Markup Template Engine is another view technology which is supported by Spring. Let's see a quick example to learn how to use it.


Maven dependency



Java Config class

public class MyWebConfig extends WebMvcConfigurerAdapter {

  public void configureViewResolvers (ViewResolverRegistry registry) {

  public GroovyMarkupConfigurer groovyMarkupConfigurer () {
      GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
      return configurer;
  • GroovyMarkupConfigurer

    This Spring extension of Groovy's TemplateConfiguration configures and creates the groovy's MarkupTemplateEngine. The property resourceLoaderPath sets the Groovy Markup Template resource loader path(s) via a Spring resource location.

  • WebMvcConfigurerAdapter#configureViewResolvers

    The method ViewResolverRegistry#groovy() registers an instance of GroovyMarkupViewResolver as bean. Alternatively, we can register the bean ourselves:
     public ViewResolver groovyViewResolver () {
        GroovyMarkupViewResolver viewResolver = new GroovyMarkupViewResolver();
        return viewResolver;

Writing a Spring Controller

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

The Groovy Markup template


yieldUnescaped '<!DOCTYPE html>'
html(lang:'en') {
    head {
        meta('http-equiv':'"Content-Type" content="text/html; charset=utf-8"')
        title('My page')
    body {
        h2 ('A Groovy View with Spring MVC')
        div ("msg: $msg")
        div ("time: $time")

You can find more info about the groovy markup template here.


The generated html:

<!DOCTYPE html><html lang='en'><head><meta http-equiv='"Content-Type" content="text/html; charset=utf-8"'/><title>My page</title></head><body><h2>A Groovy View with Spring MVC</h2><div>msg: A message from the controller</div><div>time: 18:47:38.514</div></body></html>

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.3.10.RELEASE: Spring Web MVC.
  • groovy-templates 2.4.12: Groovy: A powerful, dynamic language for the JVM.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

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

    See Also