前言:本文基于上一篇内容-Spring+SpringMVC项目搭建
Thymeleaf简介
Thymeleaf是个XML/XHTML/HTML5模板引擎,可以用于Web与非Web应用。Thymeleaf很大的一个特点就是,它支持使用html格式的文件作为模版,这个虽然与JSP相比只是一个小改动,但是却影响很大,因为html文件可以直接浏览器运行查看;Thymeleaf另外一大特点就是它的标签语法,在程序中它的标签是执行代码,在程序外通过浏览器直接查看html文件时,它的标签又丝毫不会对内容产生影响,所以很是方便工作中UI、前端、开发之间的合作。个人观点,仅供参考。
在SpringMVC环境搭建好后,只需要做一点很简单的改动就可以将SP模板替换为Thymeleaf模板。
pom.xml文件修改,配置Thymeleaf模板所需依赖,以及对Spring支持的JAR包依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
修改applicationContext-servlet.xml文件配置
<!-- 注释掉JSP视图解析器配置 -->
<!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean> -->
<!-- Thymeleaf视图模板引擎配置 -->
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<!-- 视图解析器配置 -->
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="order" value="1" />
<!-- <property name="viewNames" value="*.html,*.xhtml" /> -->
</bean>
好了,改造完成。下面做下小测试,MyTestController.java文件保持不变,根据视图解析器配置,在目录/WEB-INF/templates/下创建MyTest.html文件,并引入Thymeleaf的引用,并写个简单的标签测试一下。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>Insert title here</title>
</head>
<body>
<span th:text="Hello">This is MyTest page with Thymeleaf!</span>
</body>
</html>
至此,打包项目、部署,访问http://localhost:8080/SpringDemo/myTest,看到页面显示着“Hello”,结束。如果想用好Thymeleaf,还少不了要多学习学习它的各种标签及用法。