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.
Example
Maven dependency
pom.xml<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-templates</artifactId>
<version>2.4.12</version>
</dependency>
Java Config class
@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureViewResolvers (ViewResolverRegistry registry) {
registry.groovy();
}
@Bean
public GroovyMarkupConfigurer groovyMarkupConfigurer () {
GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
configurer.setResourceLoaderPath("/WEB-INF/views/");
return configurer;
}
}
Writing a Spring 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";
}
}
The Groovy Markup template
src/main/webapp/WEB-INF/views/my-page.tplyieldUnescaped '<!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.
Output
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 ProjectDependencies 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
|