原文: http://zetcode.com/spring/thymeleaf/

Spring Thymeleaf 教程展示了如何在 Spring 应用中使用 Thymeleaf 模板引擎。

Spring 是用于创建企业应用的流行 Java 应用框架。

Thymeleaf

Thymeleaf 是适用于 Web 和独立环境的服务器端 Java 模板引擎。 它提供了完整的 Spring Framework 集成。

Spring Thymeleaf 示例

以下应用使用 Thymeleaf 生成视图。

  1. pom.xml
  2. src
  3. ├───main
  4. ├───java
  5. └───com
  6. └───zetcode
  7. ├───config
  8. MyWebInitializer.java
  9. WebConfig.java
  10. ├───controller
  11. MyController.java
  12. └───service
  13. WordService.java
  14. └───resources
  15. logback.xml
  16. └───templates
  17. index.html
  18. showWords.html
  19. └───test
  20. └───java

这是项目结构。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>springthymeleafex</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>war</packaging>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <maven.compiler.source>11</maven.compiler.source>
  14. <maven.compiler.target>11</maven.compiler.target>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>javax.servlet</groupId>
  19. <artifactId>javax.servlet-api</artifactId>
  20. <version>4.0.1</version>
  21. <scope>provided</scope>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework</groupId>
  25. <artifactId>spring-webmvc</artifactId>
  26. <version>5.1.4.RELEASE</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.thymeleaf</groupId>
  30. <artifactId>thymeleaf-spring5</artifactId>
  31. <version>3.0.11.RELEASE</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.thymeleaf</groupId>
  35. <artifactId>thymeleaf</artifactId>
  36. <version>3.0.11.RELEASE</version>
  37. </dependency>
  38. </dependencies>
  39. <build>
  40. <plugins>
  41. <plugin>
  42. <groupId>org.apache.maven.plugins</groupId>
  43. <artifactId>maven-war-plugin</artifactId>
  44. <version>3.2.2</version>
  45. </plugin>
  46. <plugin>
  47. <groupId>org.eclipse.jetty</groupId>
  48. <artifactId>jetty-maven-plugin</artifactId>
  49. <version>9.4.14.v20181114</version>
  50. </plugin>
  51. </plugins>
  52. </build>
  53. </project>

pom.xml中,我们具有必要的依赖项。

resources/logback.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3. <logger name="org.springframework" level="ERROR"/>
  4. <logger name="com.zetcode" level="INFO"/>
  5. <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
  6. <encoder>
  7. <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
  8. </Pattern>
  9. </encoder>
  10. </appender>
  11. <root>
  12. <level value="INFO" />
  13. <appender-ref ref="consoleAppender" />
  14. </root>
  15. </configuration>

logback.xml是 Logback 日志库的配置文件。

com/zetcode/config/MyWebInitializer.java

  1. package com.zetcode.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  4. @Configuration
  5. public class MyWebInitializer extends
  6. AbstractAnnotationConfigDispatcherServletInitializer {
  7. @Override
  8. protected Class<?>[] getRootConfigClasses() {
  9. return null;
  10. }
  11. @Override
  12. protected Class<?>[] getServletConfigClasses() {
  13. return new Class[]{WebConfig.class};
  14. }
  15. @Override
  16. protected String[] getServletMappings() {
  17. return new String[]{"/"};
  18. }
  19. }

MyWebInitializer注册 Spring DispatcherServlet,它是 Spring Web 应用的前端控制器。

  1. @Override
  2. protected Class<?>[] getServletConfigClasses() {
  3. return new Class[]{WebConfig.class};
  4. }

getServletConfigClasses()返回 Web 配置类。

com/zetcode/config/WebConfig.java

  1. package com.zetcode.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.ComponentScan;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.web.servlet.ViewResolver;
  8. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  9. import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
  10. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  11. import org.thymeleaf.spring5.SpringTemplateEngine;
  12. import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
  13. import org.thymeleaf.spring5.view.ThymeleafViewResolver;
  14. @Configuration
  15. @EnableWebMvc
  16. @ComponentScan(basePackages = {"com.zetcode"})
  17. public class WebConfig implements WebMvcConfigurer {
  18. @Autowired
  19. private ApplicationContext applicationContext;
  20. @Bean
  21. public SpringResourceTemplateResolver templateResolver() {
  22. var templateResolver = new SpringResourceTemplateResolver();
  23. templateResolver.setApplicationContext(applicationContext);
  24. templateResolver.setPrefix("classpath:/templates/");
  25. templateResolver.setSuffix(".html");
  26. return templateResolver;
  27. }
  28. @Bean
  29. public SpringTemplateEngine templateEngine() {
  30. var templateEngine = new SpringTemplateEngine();
  31. templateEngine.setTemplateResolver(templateResolver());
  32. templateEngine.setEnableSpringELCompiler(true);
  33. return templateEngine;
  34. }
  35. @Bean
  36. public ViewResolver viewResolver() {
  37. var resolver = new ThymeleafViewResolver();
  38. var registry = new ViewResolverRegistry(null, applicationContext);
  39. resolver.setTemplateEngine(templateEngine());
  40. registry.viewResolver(resolver);
  41. return resolver;
  42. }
  43. }

WebConfig配置 Thymeleaf 模板引擎。 我们将模板文件的位置设置为classpath上的templates目录。 (resources在类路径上。)

com/zetcode/service/WordService.java

  1. package com.zetcode.service;
  2. import org.springframework.stereotype.Service;
  3. import java.util.List;
  4. @Service
  5. public class WordService {
  6. private final List<String> words = List.of("pen", "sky",
  7. "rock", "forest", "falcon", "eagle");
  8. public List<String> all() {
  9. return words;
  10. }
  11. }

WordService返回几个字。

com/zetcode/controller/MyController.java

  1. package com.zetcode.controller;
  2. import com.zetcode.service.WordService;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. @Controller
  7. public class MyController {
  8. @GetMapping(value = "/")
  9. public String home() {
  10. return "index";
  11. }
  12. @GetMapping(value = "/words")
  13. public String showWords(Model model, WordService wordService) {
  14. var words = wordService.all();
  15. model.addAttribute("words", words);
  16. return "showWords";
  17. }
  18. }

MyController提供请求路径和处理器方法之间的映射。 我们有两个映射:home页面和showWords页面。

  1. var words = wordService.all();
  2. model.addAttribute("words", words);

我们使用wordService检索所有单词并将其放入模型中。 该模型将传递给 Thymeleaf,后者将处理模板中的数据。

resources/templates/index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Home page</title>
  6. </head>
  7. <body>
  8. <p>
  9. <a href="words">Show words</a>
  10. </p>
  11. </body>
  12. </html>

主页包含显示所有单词的锚点。

resources/templates/showWords.html

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <title>Words</title>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. </head>
  8. <body>
  9. <h2>List of words</h2>
  10. <ul th:each="word : ${words}">
  11. <li th:text="${word}">word</li>
  12. </ul>
  13. </body>
  14. </html>

使用 Thymeleaf 的th:each指令,我们可以显示 HTML 列表中的所有单词。

  1. $ mvn jetty:run

我们运行服务器并定位到localhost:8080以获取具有锚点的主页。

在本教程中,我们使用了Thymeleaf模板引擎。

您可能对这些相关教程也感兴趣: Spring Freemarker 教程Spring @Configuration教程Java 教程或列出所有 Spring 教程