Spring Boot - Using Groovy View

[Updated: Jan 11, 2018, Created: Jan 11, 2018]

To use Groovy in Spring Boot application, we just need to include spring-boot-starter-groovy-templates dependency and place the template file under src/main/resources/templates/ directory. The rest of the configurations is done automatically by Spring Boot. Also check out our Groovy example with plain MVC.

Example

Maven dependencies

pom.xml

<project .....>
<modelVersion>4.0.0</modelVersion>
<groupId>com.logicbig.example</groupId>
<artifactId>spring-boot-groovy-example</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-groovy-templates</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Groovy Template File

/src/main/resources/templates/my-page.tpl

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 + Spring Boot')
        div ("msg: $msg")
        div ("time: $time")
    }
}

Spring MVC Controller

@Controller
@RequestMapping("/")
public class MyController {

  @RequestMapping
  public String handleRequest(Model model) {
      model.addAttribute("msg", "A message from the controller");
      model.addAttribute("time", LocalTime.now());
      return "my-page";
  }
}

Spring boot main class

@SpringBootApplication
public class ExampleMain {

  public static void main(String[] args) throws InterruptedException {
      SpringApplication.run(ExampleMain.class, args);
  }
}

To try examples, run spring-boot maven plugin (configured in pom.xml of example project below):

mvn spring-boot:run

We can also run the main class from our IDE.

Output

Example Project

Dependencies and Technologies Used :

  • spring-boot-starter-groovy-templates 1.5.9.RELEASE: Starter for building MVC web applications using Groovy Templates views.
    Corresponding Spring version: 4.3.13.RELEASE
  • JDK 1.8
  • Maven 3.3.9

Spring Boot - Groovy View Example Select All Download
  • spring-boot-Groovy-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
          • templates

See Also