SpringMVC项目使用Thymeleaf模板引擎

前言:本文基于上一篇内容-Spring+SpringMVC项目搭建html

Thymeleaf简介前端

Thymeleaf是个XML/XHTML/HTML5模板引擎,能够用于Web与非Web应用。Thymeleaf很大的一个特色就是,它支持使用html格式的文件做为模版,这个虽然与JSP相比只是一个小改动,可是却影响很大,由于html文件能够直接浏览器运行查看;Thymeleaf另一大特色就是它的标签语法,在程序中它的标签是执行代码,在程序外经过浏览器直接查看html文件时,它的标签又丝绝不会对内容产生影响,因此非常方便工做中UI、前端、开发之间的合做。我的观点,仅供参考。java

  • 在SpringMVC环境搭建好后,只须要作一点很简单的改动就能够将SP模板替换为Thymeleaf模板。
    web

  • pom.xml文件修改,配置Thymeleaf模板所需依赖,以及对Spring支持的JAR包依赖spring

<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的引用,并写个简单的标签测试一下。app

<!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,还少不了要多学习学习它的各类标签及用法。jsp

相关文章
相关标签/搜索