Thymeleaf项目实践

您所在的位置:网站首页 thymeleaf官网 Thymeleaf项目实践

Thymeleaf项目实践

#Thymeleaf项目实践 | 来源: 网络整理| 查看: 265

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

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

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

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

/* * ============================================================================= * * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package com.yiibai.business.services; import java.util.List; import com.yiibai.business.entities.Product; import com.yiibai.business.entities.repositories.ProductRepository; public class ProductService { public ProductService() { super(); } public List findAll() { return ProductRepository.getInstance().findAll(); } public Product findById(final Integer id) { return ProductRepository.getInstance().findById(id); } }

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

/* * ============================================================================= * * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package com.yiibai.web.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.thymeleaf.ITemplateEngine; import com.yiibai.business.entities.User; import com.yiibai.web.application.GTVGApplication; import com.yiibai.web.controller.IGTVGController; public class GTVGFilter implements Filter { private ServletContext servletContext; private GTVGApplication application; public GTVGFilter() { super(); } private static void addUserToSession(final HttpServletRequest request) { // Simulate a real user session by adding a user object request.getSession(true).setAttribute("user", new User("John", "Apricot", "Antarctica", null)); } public void init(final FilterConfig filterConfig) throws ServletException { this.servletContext = filterConfig.getServletContext(); this.application = new GTVGApplication(this.servletContext); } public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { addUserToSession((HttpServletRequest)request); if (!process((HttpServletRequest)request, (HttpServletResponse)response)) { chain.doFilter(request, response); } } public void destroy() { // nothing to do } private boolean process(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { // This prevents triggering engine executions for resource URLs if (request.getRequestURI().startsWith("/css") || request.getRequestURI().startsWith("/images") || request.getRequestURI().startsWith("/favicon")) { return false; } /* * Query controller/URL mapping and obtain the controller * that will process the request. If no controller is available, * return false and let other filters/servlets process the request. */ IGTVGController controller = this.application.resolveControllerForRequest(request); if (controller == null) { return false; } /* * Obtain the TemplateEngine instance. */ ITemplateEngine templateEngine = this.application.getTemplateEngine(); /* * Write the response headers */ response.setContentType("text/html;"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); /* * Execute the controller and process view template, * writing the results to the response writer. */ controller.process( request, response, this.servletContext, templateEngine); return true; } catch (Exception e) { try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (final IOException ignored) { // Just ignore this } throw new ServletException(e); } } }

下面是IGTVGController接口的代码:

/* * ============================================================================= * * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package com.yiibai.web.controller; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.thymeleaf.ITemplateEngine; public interface IGTVGController { public void process( HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, ITemplateEngine templateEngine) throws Exception; }

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

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

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

创建和配置模板引擎

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

ITemplateEngine templateEngine = this.application.getTemplateEngine();

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

public class GTVGApplication { ... private final TemplateEngine templateEngine; ... public GTVGApplication(final ServletContext servletContext) { super(); ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext); // HTML is the default mode, but we set it anyway for better understanding of code templateResolver.setTemplateMode(TemplateMode.HTML); // This will convert "home" to "/WEB-INF/templates/home.html" templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); // Template cache TTL=1h. If not set, entries would be cached until expelled by LRU templateResolver.setCacheTTLMs(Long.valueOf(3600000L)); // Cache is set to true by default. Set to false if you want templates to // be automatically updated when modified. templateResolver.setCacheable(true); this.templateEngine = new TemplateEngine(); this.templateEngine.setTemplateResolver(templateResolver); ... } }

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

模板解析器

从模板解析器开始:

ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);

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

public interface ITemplateResolver { ... /* * Templates are resolved by their name (or content) and also (optionally) their * owner template in case we are trying to resolve a fragment for another template. * Will return null if template cannot be handled by this template resolver. */ public TemplateResolution resolveTemplate( final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Map templateResolutionAttributes); }

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

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

templateResolver.setTemplateMode(TemplateMode.HTML);

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

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

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

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

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

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

templateResolver.setCacheTTLMs(3600000L);

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

模板引擎

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

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

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

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

我们的模板引擎已准备就绪,就可以使用Thymeleaf开始创建页面了。有关项目的代码,可以从: https://pan.baidu.com/s/1nwBa9Gd 下载。

  

上一篇: Thymeleaf表单 下一篇:哥,这回真没有了 加QQ群啦,易百教程官方技术学习群 注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3