Introduction Thymeleaf Groovy Markup Templates

4.3.9.RELEASE Spring Framework 564

23. View technologies

23.1 Introduction

One of the areas in which Spring excels is in the separation of view technologies from the rest of the MVC framework. For example, deciding to use Groovy Markup Templates or Thymeleaf in place of an existing JSP is primarily a matter of configuration. This chapter covers the major view technologies that work with Spring and touches briefly on how to add new ones. This chapter assumes you are already familiar with Section 22.5, “Resolving views” which covers the basics of how views in general are coupled to the MVC framework.

23.2 Thymeleaf

Thymeleaf is a good example of a view technology fitting perfectly in the MVC framework. Support for this integration is not provided by the Spring team but by the Thymeleaf team itself. Configuring Thymeleaf for Spring usually requires a few beans defined, like a ServletContextTemplateResolver , a SpringTemplateEngine and a ThymeleafViewResolver . Please refer to the Thymeleaf+Spring documentation section for more details.

23.3 Groovy Markup Templates

The Groovy Markup Template Engine is another view technology, supported by Spring. This template engine is a template engine primarily aimed at generating XML-like markup XML, XHTML, HTML5, … , but that can be used to generate any text based content. This requires Groovy 2.3.1+ on the classpath. Configuration Configuring the Groovy Markup Template Engine is quite easy: Configuration EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { Override public void configureViewResolversViewResolverRegistry registry { registry.groovy; } Bean public GroovyMarkupConfigurer groovyMarkupConfigurer { GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer; configurer.setResourceLoaderPath WEB-INF ; return configurer; } } The XML counterpart using the MVC namespace is: mvc:annotation-driven mvc:view-resolvers mvc:groovy mvc:view-resolvers mvc:groovy-configurer resource-loader-path = WEB-INF 4.3.9.RELEASE Spring Framework 565 Example Unlike traditional template engines, this one relies on a DSL that uses the builder syntax. Here is a sample template for an HTML page: yieldUnescaped DOCTYPE html htmllang: en { head { meta http-equiv : Content-Type content=texthtml; charset=utf-8 title My page } body { p This is an example of HTML contents } }

23.4 Velocity FreeMarker