Thymeleaf 使用分享
1. Thymeleaf简介
1.1 Thymeleaf使用背景
虽然JSP已经使用了较长的时间,并且在Java web中使用的也很广泛,但是它也有自身的一些缺陷。明显的就是JSP是以HTML或者XML的形式展现的。大多数的JSP模版都使用HTML的格式,并使用各种JSP标签库。虽然这些标签库可以在JSP中进行动态的解析,但是却很难有一个格式良好的页面。比如,可以在HTML中使用下面的JSP标签:
<input type="text" value="<c:out value="${thing.name}"/>" />
当阅读一个没有解析的JSP页面时,常常很难读懂,简直就是一场视觉灾难!因为JSP并不是真正的HTML,很多web浏览器和编辑器很难对JSP进行解析。
另外,JSP与servlet规范是紧密耦合的,这就意味着它只能使用在以servlet为基础的web应用中。
近年内有涌现出很多要替代JSP作为java应用的视图技术,其中一个有力的竞争者就是:Thymeleaf。Thymeleaf不需要依赖标签库,并且是可编辑的、可以解析到HTML中。另外,它与servlet规范是没有耦合的,因此它可以在JSP不能使用的环境进行使用。下面,我们来看一下如何在Spring MVC中使用Thymeleaf。
1.2 Thymeleaf介绍
- Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可。
- Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。
- Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。
- Thymeleaf主要通过HTML的标签属性渲染标签内容,浏览器在解析html时,当检查到Thymeleaf的属性时候会忽略,
- 所以Thymeleaf的模板可以通过浏览器直接打开展现,这样非常有利于前后端的分离。
2. SpringMVC + Thymeleaf 整合使用
搭建好SpringMVC开发环境后,接下来就可以整合Thymeleaf模板引擎。
2.1 Thymeleaf 添加 Maven 依赖
在pom.xml中添加以下依赖
<dependencies>
<!-- ========= Thymeleaf模板引擎 ========== -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
</dependencies>
2.2 Thymeleaf 整合 SpringMVC 环境准备
为了在Spring中使用Thymeleaf,需要配置3个bean:
1. ThymeleafViewResolver:用来从逻辑视图中解析出Thymeleaf模版;
2. SpringTemplateEngine:对模版进行处理,并给出结果;
3. TemplateResolver:用来加载Thymeleaf模版;
2.2.1 在 SpringMVC 配置文件中删除原有配置文件中,对 JSP 的解析配置
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
2.2.2 新增 Thymeleaf 配置
<!-- 模板解析器 -->
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<!-- 模板文件的路径前缀 -->
<property name="prefix" value="/templates/" />
<!-- 模板文件的路径后缀 -->
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML" />
<!-- 配置是否缓存 -->
<!-- 默认情况下, 模板缓存为true。如果您想要设置为false -->
<property name="cacheable" value="false" />
<!-- 默认编码格式 -->
<property name="characterEncoding" value="UTF-8"/>
</bean>
<!-- 模板引擎 -->
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="enableSpringELCompiler" value="true" />
</bean>
<!-- 视图解析器 -->
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="characterEncoding" value="UTF-8"/>
</bean>
2.2.3 创建模板文件夹,在 webapp 下创建 templates 文件夹放置 .html 模板文件
3. 入门 Demo 先睹为快
3.1 在templates目录下新建thymeleaf.html,内容如下:
<!DOCTYPE html>
<html lang="en"