为了更好地解释Thymeleaf处理模板所涉及的概念,本教程将使用一个演示应用程序,您可以下载本项目的应用程序。本项目是基于:Thymeleaf虚拟杂货店 的汉化修改。

这个应用程序是一个虚拟的虚拟杂货店的网站,并提供许多场景展示Thymeleaf的许多功能。

首先,我们需要为应用程序提供一组简单的模型实体:销售给客户的产品有订单信息记录。 也将管理对这些产品的注释:

1523793495346410.png

应用程序还将有一个非常简单的服务层,由Service对象组成,其中包含以下方法:

  1. /*
  2. * =============================================================================
  3. *
  4. * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org)
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * =============================================================================
  19. */
  20. package com.e-learn.business.services;
  21.  
  22. import java.util.List;
  23.  
  24. import com.e-learn.business.entities.Product;
  25. import com.e-learn.business.entities.repositories.ProductRepository;
  26.  
  27. public class ProductService {
  28.  
  29. public ProductService() {
  30. super();
  31. }
  32.  
  33. public List<Product> findAll() {
  34. return ProductRepository.getInstance().findAll();
  35. }
  36.  
  37. public Product findById(final Integer id) {
  38. return ProductRepository.getInstance().findById(id);
  39. }
  40. }

在Web层,应用程序将有一个过滤器,根据请求URL将执行委托给启用Thymeleaf的命令:

  1. /*
  2. * =============================================================================
  3. *
  4. * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org)
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * =============================================================================
  19. */
  20. package com.e-learn.web.filter;
  21.  
  22. import java.io.IOException;
  23.  
  24. import javax.servlet.Filter;
  25. import javax.servlet.FilterChain;
  26. import javax.servlet.FilterConfig;
  27. import javax.servlet.ServletContext;
  28. import javax.servlet.ServletException;
  29. import javax.servlet.ServletRequest;
  30. import javax.servlet.ServletResponse;
  31. import javax.servlet.http.HttpServletRequest;
  32. import javax.servlet.http.HttpServletResponse;
  33.  
  34. import org.thymeleaf.ITemplateEngine;
  35. import com.e-learn.business.entities.User;
  36. import com.e-learn.web.application.GTVGApplication;
  37. import com.e-learn.web.controller.IGTVGController;
  38.  
  39.  
  40. public class GTVGFilter implements Filter {
  41.  
  42. private ServletContext servletContext;
  43. private GTVGApplication application;
  44.  
  45. public GTVGFilter() {
  46. super();
  47. }
  48.  
  49. private static void addUserToSession(final HttpServletRequest request) {
  50. // Simulate a real user session by adding a user object
  51. request.getSession(true).setAttribute("user", new User("John", "Apricot", "Antarctica", null));
  52. }
  53.  
  54. public void init(final FilterConfig filterConfig) throws ServletException {
  55. this.servletContext = filterConfig.getServletContext();
  56. this.application = new GTVGApplication(this.servletContext);
  57. }
  58.  
  59. public void doFilter(final ServletRequest request, final ServletResponse response,
  60. final FilterChain chain) throws IOException, ServletException {
  61. addUserToSession((HttpServletRequest)request);
  62. if (!process((HttpServletRequest)request, (HttpServletResponse)response)) {
  63. chain.doFilter(request, response);
  64. }
  65. }
  66.  
  67. public void destroy() {
  68. // nothing to do
  69. }
  70.  
  71. private boolean process(HttpServletRequest request, HttpServletResponse response)
  72. throws ServletException {
  73. try {
  74.  
  75. // This prevents triggering engine executions for resource URLs
  76. if (request.getRequestURI().startsWith("/css") ||
  77. request.getRequestURI().startsWith("/images") ||
  78. request.getRequestURI().startsWith("/favicon")) {
  79. return false;
  80. }
  81. /*
  82. * Query controller/URL mapping and obtain the controller
  83. * that will process the request. If no controller is available,
  84. * return false and let other filters/servlets process the request.
  85. */
  86. IGTVGController controller = this.application.resolveControllerForRequest(request);
  87. if (controller == null) {
  88. return false;
  89. }
  90.  
  91. /*
  92. * Obtain the TemplateEngine instance.
  93. */
  94. ITemplateEngine templateEngine = this.application.getTemplateEngine();
  95.  
  96. /*
  97. * Write the response headers
  98. */
  99. response.setContentType("text/html;charset=UTF-8");
  100. response.setHeader("Pragma", "no-cache");
  101. response.setHeader("Cache-Control", "no-cache");
  102. response.setDateHeader("Expires", 0);
  103.  
  104. /*
  105. * Execute the controller and process view template,
  106. * writing the results to the response writer.
  107. */
  108. controller.process(
  109. request, response, this.servletContext, templateEngine);
  110.  
  111. return true;
  112.  
  113. } catch (Exception e) {
  114. try {
  115. response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  116. } catch (final IOException ignored) {
  117. // Just ignore this
  118. }
  119. throw new ServletException(e);
  120. }
  121. }
  122.  
  123. }

下面是IGTVGController接口的代码:

  1. /*
  2. * =============================================================================
  3. *
  4. * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org)
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * =============================================================================
  19. */
  20. package com.e-learn.web.controller;
  21.  
  22. import javax.servlet.ServletContext;
  23. import javax.servlet.http.HttpServletRequest;
  24. import javax.servlet.http.HttpServletResponse;
  25.  
  26. import org.thymeleaf.ITemplateEngine;
  27.  
  28. public interface IGTVGController {
  29.  
  30. public void process(
  31. HttpServletRequest request, HttpServletResponse response,
  32. ServletContext servletContext, ITemplateEngine templateEngine)
  33. throws Exception;
  34.  
  35. }

我们现在要做的就是创建IGTVGController接口的实现,从服务中检索数据并使用ITemplateEngine对象处理模板。

最后,它会看起来得到类似下面的页面:

1523793498490274.png

但首先来看看这个模板引擎是如何初始化的。

创建和配置模板引擎

过滤器中的process(…)方法包含这一行:

  1. ITemplateEngine templateEngine = this.application.getTemplateEngine();

GTVGApplication类负责创建和配置Thymeleaf应用程序中最重要的对象之一:TemplateEngine实例(实现ITemplateEngine接口)。org.thymeleaf.TemplateEngine对象是这样初始化的:

  1. public class GTVGApplication {
  2.  
  3.  
  4. ...
  5. private final TemplateEngine templateEngine;
  6. ...
  7.  
  8.  
  9. public GTVGApplication(final ServletContext servletContext) {
  10.  
  11. super();
  12.  
  13. ServletContextTemplateResolver templateResolver =
  14. new ServletContextTemplateResolver(servletContext);
  15.  
  16. // HTML is the default mode, but we set it anyway for better understanding of code
  17. templateResolver.setTemplateMode(TemplateMode.HTML);
  18. // This will convert "home" to "/WEB-INF/templates/home.html"
  19. templateResolver.setPrefix("/WEB-INF/templates/");
  20. templateResolver.setSuffix(".html");
  21. // Template cache TTL=1h. If not set, entries would be cached until expelled by LRU
  22. templateResolver.setCacheTTLMs(Long.valueOf(3600000L));
  23.  
  24. // Cache is set to true by default. Set to false if you want templates to
  25. // be automatically updated when modified.
  26. templateResolver.setCacheable(true);
  27.  
  28. this.templateEngine = new TemplateEngine();
  29. this.templateEngine.setTemplateResolver(templateResolver);
  30.  
  31. ...
  32.  
  33. }
  34.  
  35. }

配置TemplateEngine对象的方法有很多种,但现在这几行代码将足以教会需要的步骤。

模板解析器

从模板解析器开始:

  1. ServletContextTemplateResolver templateResolver =
  2. new ServletContextTemplateResolver(servletContext);

模板解析器是实现来自Thymeleaf API(名为org.thymeleaf.templateresolver.ITemplateResolver)的接口的对象:

  1. public interface ITemplateResolver {
  2.  
  3. ...
  4.  
  5. /*
  6. * Templates are resolved by their name (or content) and also (optionally) their
  7. * owner template in case we are trying to resolve a fragment for another template.
  8. * Will return null if template cannot be handled by this template resolver.
  9. */
  10. public TemplateResolution resolveTemplate(
  11. final IEngineConfiguration configuration,
  12. final String ownerTemplate, final String template,
  13. final Map<String, Object> templateResolutionAttributes);
  14. }

这些对象负责确定模板将如何被访问,并且在这个GTVG应用程序中,org.thymeleaf.templateresolver.ServletContextTemplateResolver意味着我们要从Servlet上下文中检索我们的模板文件作为资源:一个应用程序范围的javax .servlet.ServletContext对象,它存在于每个Java Web应用程序中,并解析来自Web应用程序根目录的资源。

但这并不是我们说的模板解析器,因为可以在其上设置一些配置参数。 首先,模板模式:

  1. templateResolver.setTemplateMode(TemplateMode.HTML);

HTML是ServletContextTemplateResolver的默认模板模式,但最好还是建立它,以便可以清楚知道代码执行了什么。

  1. templateResolver.setPrefix("/WEB-INF/templates/");
  2. templateResolver.setSuffix(".html");

前缀和后缀修改了将传递给引擎以获取要使用的真实资源名称的模板名称。

使用此配置,模板名称“product/list”将对应于:

  1. servletContext.getResourceAsStream("/WEB-INF/templates/product/list.html")

可选地,解析模板可以存储在缓存中的时间量是通过cacheTTLMs属性在模板解析器中配置:

  1. templateResolver.setCacheTTLMs(3600000L);

如果达到最大高速缓存大小并且它是当前高速缓存的最旧条目,则在达到TTL之前,模板仍可从高速缓存中排除。

模板引擎

模板引擎对象是org.thymeleaf.ITemplateEngine接口的实现。 其中一个实现由Thymeleaf核心提供:org.thymeleaf.TemplateEngine,在这里创建一个实例:

  1. templateEngine = new TemplateEngine();
  2. templateEngine.setTemplateResolver(templateResolver);

很简单,不是吗? 需要的只是创建一个实例并为其设置模板解析器。

模板解析器是TemplateEngine需要的唯一必需的参数,不过稍后还会介绍其他许多参数(消息解析器,缓存大小等)。