Mesin Templat untuk Musim Bunga

1. Gambaran keseluruhan

Kerangka web Spring dibina di sekitar corak MVC (Model-View-Controller), yang menjadikannya lebih mudah untuk memisahkan masalah dalam aplikasi. Ini memungkinkan kemungkinan untuk menggunakan teknologi pandangan yang berbeza, dari teknologi JSP yang mapan hingga berbagai mesin templat.

Dalam artikel ini, kita akan melihat mesin templat utama yang dapat digunakan dengan Spring, konfigurasi mereka, dan contoh penggunaannya.

2. Teknologi Spring View

Memandangkan keprihatinan dalam aplikasi Spring MVC dipisahkan dengan bersih dari teknologi satu pandangan ke yang lain terutama adalah masalah konfigurasi.

Untuk membuat setiap jenis paparan, kita perlu menentukan kacang ViewResolver yang sesuai dengan setiap teknologi. Ini bermaksud bahawa kita kemudian dapat mengembalikan nama pandangan dari kaedah pemetaan @Controller dengan cara yang sama seperti biasanya kita mengembalikan fail JSP.

Pada bahagian berikut, kita akan membahas lebih banyak teknologi tradisional seperti Java Server Pages , serta mesin templat utama yang dapat digunakan dengan Spring: Thymeleaf , Groovy , FreeMarker, Jade.

Untuk masing-masing, kami akan membahas konfigurasi yang diperlukan dalam aplikasi Spring standard dan aplikasi yang dibina menggunakan Spring Boot .

3. Halaman Pelayan Java

JSP adalah salah satu teknologi pandangan yang paling popular untuk aplikasi Java, dan disokong oleh Spring out-of-the-box. Untuk membuat fail JSP, jenis kacang ViewResolver yang biasa digunakan adalah InternalResourceViewResolver :

@EnableWebMvc @Configuration public class ApplicationConfiguration implements WebMvcConfigurer { @Bean public ViewResolver jspViewResolver() { InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setPrefix("/WEB-INF/views/"); bean.setSuffix(".jsp"); return bean; } }

Seterusnya, kita boleh mula membuat fail JSP di lokasi / WEB-INF / paparan :

    User Registration    Email:   Password:      

Sekiranya kita menambahkan fail ke aplikasi Spring Boot , maka bukannya di kelas ApplicationConfiguration , kita dapat menentukan sifat berikut dalam file application.properties :

spring.mvc.view.prefix: /WEB-INF/views/ spring.mvc.view.suffix: .jsp

Berdasarkan sifat ini, Spring Boot akan mengkonfigurasi secara automatik ViewResolver yang diperlukan .

4. Thymeleaf

Thymeleaf adalah mesin templat Java yang dapat memproses fail HTML, XML, teks, JavaScript atau CSS. Tidak seperti mesin templat lain, Thymeleaf membenarkan penggunaan templat sebagai prototaip, yang bermaksud ia dapat dilihat sebagai fail statik.

4.1. Ketergantungan Maven

Untuk mengintegrasikan Thymeleaf dengan Spring, kita perlu menambahkan kebergantungan thymeleaf dan thymeleaf-spring4 :

 org.thymeleaf thymeleaf 3.0.11.RELEASE   org.thymeleaf thymeleaf-spring5 3.0.11.RELEASE 

Sekiranya kita mempunyai projek Spring 4, maka kita perlu menambahkan thymeleaf-spring4 .

4.2. Konfigurasi Musim Bunga

Seterusnya, kita perlu menambahkan konfigurasi yang memerlukan kacang SpringTemplateEngine , serta kacang TemplateResolver yang menentukan lokasi dan jenis fail pandangan.

The SpringResourceTemplateResolver disepadukan dengan mekanisme penyelesaian sumber Spring:

@Configuration @EnableWebMvc public class ThymeleafConfiguration { @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(thymeleafTemplateResolver()); return templateEngine; } @Bean public SpringResourceTemplateResolver thymeleafTemplateResolver() { SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setPrefix("/WEB-INF/views/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); return templateResolver; } }

Juga, kita memerlukan ViewResolver kacang jenis ThymeleafViewResolver :

@Bean public ThymeleafViewResolver thymeleafViewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); return viewResolver; }

4.3. Templat Thymeleaf

Sekarang kita dapat menambahkan fail HTML di lokasi WEB-INF / paparan :

   User Registration    Email: Password:    

Templat Thymeleaf sangat serupa dalam sintaks ke templat HTML.

Beberapa ciri yang tersedia semasa menggunakan aplikasi Thymeleaf di Spring adalah:

    • sokongan untuk menentukan bentuk tingkah laku
    • input bentuk yang mengikat pada model data
    • pengesahan untuk input borang
    • memaparkan nilai dari sumber mesej
    • serpihan templat rendering

You can read more about using Thymeleaf templates in our article Thymeleaf in Spring MVC.

4.4. Thymeleaf in Spring Boot

Spring Boot will provide auto-configuration for Thymeleaf by adding the spring-boot-starter-thymeleaf dependency:

 org.springframework.boot spring-boot-starter-thymeleaf 2.3.3.RELEASE 

No explicit configuration is necessary. By default, HTML files should be placed in the resources/templates location.

5. FreeMarker

FreeMarker is a Java-based template engine built by the Apache Software Foundation. It can be used to generate web pages, but also source code, XML files, configuration files, emails and other text-based formats.

The generation is done based on template files written using the FreeMarker Template Language.

5.1. Maven Dependencies

To start using the templates in our project, we need the freemarker dependency:

 org.freemarker freemarker 2.3.23 

For Spring integration, we also need the spring-context-support dependency:

 org.springframework spring-context-support 5.2.8.RELEASE 

5.2. Spring Configuration

Integrating FreeMarker with Spring MVC requires defining a FreemarkerConfigurer bean which specifies the location of the template files:

@Configuration @EnableWebMvc public class FreemarkerConfiguration { @Bean public FreeMarkerConfigurer freemarkerConfig() { FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/"); return freeMarkerConfigurer; } }

Next, we need to define an appropriate ViewResolver bean of type FreeMarkerViewResolver:

@Bean public FreeMarkerViewResolver freemarkerViewResolver() { FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); resolver.setCache(true); resolver.setPrefix(""); resolver.setSuffix(".ftl"); return resolver; }

5.3. FreeMarker Templates

We can create an HTML template using FreeMarker in the WEB-INF/views location:

    User Registration     Email:  Password:     

In the example above, we have imported a set of macros defined by Spring for working with forms in FreeMarker, including binding form inputs to data models.

Also, the FreeMarker Template Language contains a large number of tags, directives, and expressions for working with collections, flow control structures, logical operators, formatting and parsing strings, numbers and many more features.

5.4. FreeMarker in Spring Boot

In a Spring Boot application, we can simplify the needed configuration by using the spring-boot-starter-freemarker dependency:

 org.springframework.boot spring-boot-starter-freemarker 2.3.3.RELEASE 

This starter adds the necessary auto-configuration. All we need to do is start placing our template files in the resources/templates folder.

6. Groovy

Spring MVC views can also be generated using the Groovy Markup Template Engine. This engine is based on a builder syntax and can be used for generating any text format.

6.1. Maven Dependencies

The groovy-templates dependency needs to be added to our pom.xml:

 org.codehaus.groovy groovy-templates 2.4.12 

6.2. Spring Configuration

The integration of the Markup Template Engine with Spring MVC requires defining a GroovyMarkupConfigurer bean and a ViewResolver of type GroovyMarkupViewResolver:

@Configuration @EnableWebMvc public class GroovyConfiguration { @Bean public GroovyMarkupConfigurer groovyMarkupConfigurer() { GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer(); configurer.setResourceLoaderPath("/WEB-INF/views/"); return configurer; } @Bean public GroovyMarkupViewResolver thymeleafViewResolver() { GroovyMarkupViewResolver viewResolver = new GroovyMarkupViewResolver(); viewResolver.setSuffix(".tpl"); return viewResolver; } }

6.3. Groovy Markup Templates

Templates are written in the Groovy language and have several characteristics:

    • they are compiled into bytecode
    • they contain support for fragments and layouts
    • they provide support for internationalization
    • the rendering is fast

Let's create a Groovy template for our “User Registration” form, which includes data bindings:

yieldUnescaped '' html(lang:'en') { head { meta('http-equiv':'"Content-Type" ' + 'content="text/html; charset=utf-8"') title('User Registration') } body { form (id:'userForm', action:'register', method:'post') { label (for:'email', 'Email') input (name:'email', type:'text', value:user.email?:'') label (for:'password', 'Password') input (name:'password', type:'password', value:user.password?:'') div (class:'form-actions') { input (type:'submit', value:'Submit') } } } }

6.4. Groovy Template Engine in Spring Boot

Spring Boot contains auto-configuration for the Groovy Template Engine, which is added by including the spring-boot-starter-groovy-templates dependency:

 org.springframework.boot spring-boot-starter-groovy-templates 2.3.3.RELEASE 

The default location for the templates is /resources/templates.

7. Jade4j

Jade4j is the Java implementation of the Pug template engine (originally known as Jade) for Javascript. Jade4j templates can be used for generating HTML files.

7.1. Maven Dependencies

For Spring integration, we need the spring-jade4j dependency:

 de.neuland-bfi spring-jade4j 1.2.5 

7.2. Spring Configuration

To use Jade4j with Spring, we have to define a SpringTemplateLoader bean that configures the location of the templates, as well as a JadeConfiguration bean:

@Configuration @EnableWebMvc public class JadeTemplateConfiguration { @Bean public SpringTemplateLoader templateLoader() { SpringTemplateLoader templateLoader = new SpringTemplateLoader(); templateLoader.setBasePath("/WEB-INF/views/"); templateLoader.setSuffix(".jade"); return templateLoader; } @Bean public JadeConfiguration jadeConfiguration() { JadeConfiguration configuration = new JadeConfiguration(); configuration.setCaching(false); configuration.setTemplateLoader(templateLoader()); return configuration; } }

Next, we need the usual ViewResolver bean, in this case of type JadeViewResolver:

@Bean public ViewResolver viewResolver() { JadeViewResolver viewResolver = new JadeViewResolver(); viewResolver.setConfiguration(jadeConfiguration()); return viewResolver; }

7.3. Jade4j Templates

Jade4j templates are characterized by an easy-to-use whitespace-sensitive syntax:

doctype html html head title User Registration body form(action="register" method="post" ) label(for="email") Email: input(type="text" name="email") label(for="password") Password: input(type="password" name="password") input(type="submit" value="Submit")

The project also provides a very useful interactive documentation, where you can view the output of your template as you write it.

Spring Boot does not provide a Jade4j starter, so in a Boot project, we would have to add the same Spring configuration as defined above.

8. Other Template Engines

Besides the template engines described so far, there are quite a few more available which may be used.

Let's review some of them briefly.

Velocity is an older template engine, which is very complex but has the disadvantage that Spring has deprecated its use since version 4.3 and removed completely in Spring 5.0.1.

JMustache adalah mesin templat yang dapat dengan mudah disatukan ke aplikasi Spring Boot dengan menggunakan ketergantungan spring-boot-starter-mustache .

Pebble mengandungi sokongan untuk Spring and Spring Boot di perpustakaannya.

Perpustakaan templat lain seperti Handlebars atau React , yang berjalan di atas mesin skrip JSR-223 seperti Nashorn, juga boleh digunakan.

9. Kesimpulannya

Dalam artikel ini, kami telah membahas beberapa mesin templat yang paling popular untuk aplikasi web Spring.

Dan, seperti biasa, kod sumber penuh contoh boleh didapati di GitHub.