什么是Thymeleaf

Thymeleaf是一个Java库。它是一个XML / XHTML / HTML5模板引擎,能够在模板文件上应用一组转换,将程序产生的数据或者文本显示到模板文件上。

Thymeleaf依赖的jar包

要使用Thymeleaf,需要在我们的web应用的classpath路径中引入相关的jar,如下:

thymeleaf-2.1.3.RELEASE.jar
ognl-3.0.6.jar
javassist-3.16.1-GA.jar
unbescape-1.0.jar
servlet-api-2.5.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
log4j-1.2.15.jar
mail-1.4.jar
activation-1.1.jar

创建模板解析器

使用Thymeleaf的前提非常简单,首先创建一个模板解析器,用来加载模板,如下:

 //Create Template Resolver
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
//ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();

创建模板解析器可以用Servlet上下文模板解析器ServletContextTemplateResolver或者类加载模板解析器ClassLoaderTemplateResolver。创建模板解析器将指定我们从Servlet上下文检索模板文件作为资源,并考虑应用程序的根路径作为资源的路径。如下:

// XHTML is the default mode, but we will set it anyway for better understanding of code
templateResolver.setTemplateMode("XHTML");
// This will convert "home" to "/WEB-INF/templates/home.html"
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");

如上所示,通过解析器创建模板节点,当使用Thymeleaf渲染名为“home”的模板的的时候,将,解析器将会自动加上前缀和后缀(扩展名)。

创建模板引擎

创建了模板解析器加载模板后,接下来需要创建一个模板引擎去做实际的处理工作,如下:

//Create Template Engine
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);

创建模板引擎很近单,只需要一个模板解析器实例。创建了关键的模板解析器和模板引擎之后,我们就可以创建模板页面使用Thymeleaf。

创建模板

我们的模板文件放在/WEB-INF/templates/路径下。创建模板文件只需要指定Thymeleaf特定的DOCTYPE和命名空间。如下:

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello thymeleaf</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>
<span th:text="#{home.welcome}">this is text will not be show</span>
</p>
</body>
</html>

如上图所示,模板文件中还定义了一个“th:text”属性,我们认为模板文件是有效的,因为我们已经通过doctype声明了Thymeleaf dtd,这个类库里面声明了这个属性。当这个模板被处理时,这个“th:text”属性将被移除,模板文件将被替换成一个严格的标准的XHTML文件。

模板文件中的th:text”属性的值是一个变量表达式,它将获取变量“hellword”的值作为<span>标签的文本显示到页面上。

创建模板上下文

为了能显示变量“hellword”的值,我们需创建模板上下文,将变量输出到模板文件中。如下图:

//Create Servlet context
WebContext ctx = new WebContext(req, resp, this.getServletContext(), req.getLocale());
ctx.setVariable("helloword","hello thymeleaf,wellcome!");

执行模板引擎

万事具备,只欠引擎没有开火。现在我们需要做的就是执行模板引擎,执行模板引擎需要传入模板名、上下文对象以及响应流。如下:

//Executing template engine
templateEngine.process("home", ctx, resp.getWriter());

让我们看看执行模板引擎后的结果:

OK,如上所说,模板文件被替换成了标准的XHTML文件了。

更多了解请访问官方网站http://www.thymeleaf.org/。

附源码:

public class thymeleafServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//Create Template Resolver
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
//ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
// XHTML is the default mode, but we will set it anyway for better understanding of code
templateResolver.setTemplateMode("XHTML");
// This will convert "home" to "/WEB-INF/templates/home.html"
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
// Set template cache TTL to 1 hour. If not set, entries would live in cache 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);
//Create Template Engine
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
//Write the response headers
resp.setContentType("text/html;charset=UTF-8");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 0);
//Create Servlet context
WebContext ctx = new WebContext(req, resp, this.getServletContext(), req.getLocale());
ctx.setVariable("helloword","hello thymeleaf,wellcome!"); //Executing template engine
templateEngine.process("home", ctx, resp.getWriter());
}
}

Thymeleaf模板引擎使用的更多相关文章

  1. (二)SpringBoot基础篇- 静态资源的访问及Thymeleaf模板引擎的使用

    一.描述 在应用系统开发的过程中,不可避免的需要使用静态资源(浏览器看的懂,他可以有变量,例:HTML页面,css样式文件,文本,属性文件,图片等): 并且SpringBoot内置了Thymeleaf ...

  2. 【Springboot】Springboot整合Thymeleaf模板引擎

    Thymeleaf Thymeleaf是跟Velocity.FreeMarker类似的模板引擎,它可以完全替代JSP,相较与其他的模板引擎,它主要有以下几个特点: 1. Thymeleaf在有网络和无 ...

  3. 三、thymeleaf模板引擎构建前台html, 后台使用 ModelAndView 和 Model 模型

    项目源码:https://github.com/y369q369/springBoot.git      ->     thymeleaf 私聊QQ: 1486866853 1.pom.xml中 ...

  4. SpringBoot使用thymeleaf模板引擎

    (1).添加pom依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactI ...

  5. Spring Boot 2.0 整合Thymeleaf 模板引擎

    本节将和大家一起实战Spring Boot 2.0 和thymeleaf 模板引擎 1. 创建项目 2. 使用Spring Initlizr 快速创建Spring Boot 应用程序 3. 填写项目配 ...

  6. Thymeleaf模板引擎的初步使用

    在springboot中,推荐使用的模板引擎是Thymeleaf模板引擎,它提供了完美的Spring MVC的支持.下面就简单的介绍一下Thymeleaf模板引擎的使用. 在controller层中, ...

  7. spring boot: thymeleaf模板引擎使用

    spring boot: thymeleaf模板引擎使用 在pom.xml加入thymeleaf模板依赖 <!-- 添加thymeleaf的依赖 --> <dependency> ...

  8. SpringBoot入门篇--使用Thymeleaf模板引擎进行页面的渲染

    在做WEB开发的时候,我们不可避免的就是在前端页面之间进行跳转,中间进行数据的查询等等操作.我们在使用SpringBoot之前包括我在内其实大部分都是用的是JSP页面,可以说使用的已经很熟悉.但是我们 ...

  9. (二)SpringBoot2.0基础篇- 静态资源的访问及Thymeleaf模板引擎的使用

    一.描述 在应用系统开发的过程中,不可避免的需要使用静态资源(浏览器看的懂,他可以有变量,例:HTML页面,css样式文件,文本,属性文件,图片等): 并且SpringBoot内置了Thymeleaf ...

  10. thymeleaf模板引擎

    thymeleaf模板引擎 thymeleaf是现代化服务器端的Java模板引擎,不同于JSP和FreeMarker,Thymeleaf的语法更加接近HTML,并且也有不错的扩展性.详细资料可以浏览官 ...

随机推荐

  1. [聊天框]让DIV的滚动条自动滚动到最底部 - 4种方法

    要制作一个在线聊天的程序,在做最后的修饰时,需要对获得的信息即时滚动以保证用户总能看到最新消息. 聊天程序是基于AJAX设计的,没有用框架,消息容器是一个DIV,所以问题就在于如何控制DIV的滚动条. ...

  2. 网站配置好了,在本地能登录系统,但是挂在IIS上就无法登录了,提示数据库连接错误

    我用的VS2010开发的网站,但是挂在本机的IIS上的时候就无法登录了,提示错误如下:

  3. objective-c可变数组

     1 #pragma mark ---------------可变数组-----------------  2 //        可以在数组里面进行增删改的操作  3 //  4 //        ...

  4. ios滑动手势全屏(这段代码实现了下一级控制器滑到上一级控制器)

    在自定义导航控制器里面加以下代码就增加全屏滑动手势 >推向前一个控制器 //  HBNavigationController.m // #import "HBNavigationCon ...

  5. A Horrible Poem(bzoj 2795)

    Description 给出一个由小写英文字母组成的字符串S,再给出q个询问,要求回答S某个子串的最短循环节.如果字符串B是字符串A的循环节,那么A可以由B重复若干次得到. Input 第一行一个正整 ...

  6. XMPP框架下微信项目总结(2)授权登陆/注销/注册/打印日志

    xmpp授权登陆步骤1 初始化xmppstream 连接服务器 传递属性jid(IP地址 端口号)2 连接成功后 传递“登”陆密码授权 3 授权后,发送在线消息xmpp所有的代理都是子线程中调用的,处 ...

  7. ios中通过调试来使用私有api

    转自:http://blog.csdn.net/cubepeng/article/details/11284173 OS不允许使用ios私有api,使用私有api可以获得意想不到的效果 ,同时使用私有 ...

  8. 【翻译十八】java-并发之锁对象

    Lock Objects Synchronized code relies on a simple kind of reentrant lock. This kind of lock is easy ...

  9. python多线程之Condition(条件变量)

    #!/usr/bin/env python # -*- coding: utf-8 -*- from threading import Thread, Condition import time it ...

  10. 分享一个最近研究的手机QQ3.0的协议(版本1.4)

    最近闲来有事, 分析了一个非常低端(非常低端的意思是说你不应该对她是否能取代你现有的QQ客户端作任何可能的奢望,她只是一个实验性的东西)的手机QQ的协议, 是手机QQ3.0,      所用到的TCP ...