Spring Boot学习笔记-Thymeleaf模板引擎的配置
写在前面
在开发过程中,使用模板引擎是很有必要的。我之前学习SSM框架,一直是使用Freemarker作为模板引擎,现在学习了Spring Boot之后,知道Spring Boot推荐使用的模板引擎是Thymeleaf,那么,对于我这种有点轻微强迫症的人来说,肯定是想赶快配置一个Thymeleaf模板引擎。经过查阅资料,配置好后,来发一篇博客记录一下配置过程。
我的Spring Boot版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath/>
</parent>
添加依赖
在项目的pom.xml
添加如下依赖:
<!-- 添加thymeleaf依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 注意,这里不需要版本号,因为如果是按照我之前的方法创建的项目,pom.xml文件里会自动添加parent结点。-->
配置thymeleaf
Thymeleaf
的配置可以在项目的application.yml
或application.properties
中配置,我这里是选择在application.yml
中配置。它的默认配置就已经满足我的需求了,我在这里主要是关闭了缓存,因为在开发过程中,如果开启缓存的话,你即使给Spring Boot
配置了热部署(下篇博客记录怎么配置热部署),你修改html
之后,仍然需要重启服务,才能看到修改后的页面,所以,强烈建议在开发过程中关闭缓存。
spring:
thymeleaf:
cache: false
# prefix: classpath:/templates/
# suffix: .html
# mode: HTML5
# encoding: UTF-8
# content-type: text/html
# 注释的部分是Thymeleaf默认的配置,如有其它需求可以自行更改
测试模板引擎
首先,我们在src/main/resources
下的templates
文件夹下新建hello.html
,内容如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<font color="red">Hello Thymeleaf.</font>
</body>
</html>
我在使用
STS
和Eclipse
创建这个文件的时候,默认meta
标签没有闭合,访问可能会报错。如果报错,请手动闭合未闭合标签。报错信息如下:
org.xml.sax.SAXParseException: The element type “meta” must be terminated by the matching end-tag “</meta>”.
在我的参考资料中,说:Thymeleaf 3.0之前要求强制闭合,3.0+版本则不要求强制闭合。
新建一个HelloController
的控制器类,代码如下:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/**
* 这里使用@Controller,而不是@RestController注解
* 因为@RestController,表示同时使用@Controller和@ResponseBody,所以会返回hello
* 而不是返回hello.html的内容。
* @author howieli
*
*/
@Controller
public class HelloController {
@GetMapping(value = "/hello")
public String helloGet() {
return "hello";
}
}
启动应用,访问
http://localhost:8080/hello
,显示如下页面,表示配置成功。
传值
传值这一块只做简单的记录,因为现在流行前后端分离。
HelloController
控制器修改如下:
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping(value = "/hello")
public String helloGet(Map<String, Object> map) {
map.put("name", "HowieLi");
return "hello";
}
}
修改
hello.html
,通过EL表达式取值:<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<font color="red">Hello Thymeleaf.</font>
<hr />
Welcome,<span th:text="${name}"></span>
</body>
</html>
重新启动应用,访问
http://localhost:8080/hello
,可以看到如下页面:
小结
其实配置很简单,知道一种模板引擎配置方法,就可以照猫画虎的配置其它模板引擎,如:Freemarker
。不过,不管配置哪个模板引擎,建议都关闭缓存,这样修改页面代码,就无需重新启动Spring Boot
,省时省力。至于修改代码等等关于热部署的配置,我的下一篇博客会记录我的配置过程。
个人博客:https://www.howieli.cn 和个人CSDN博客: http://blog.csdn.net/howieli_1995。
参考资料
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!