springboot整合thymeleaf
开始整合
在以往的开发中往往使用JSP进行页面开发,但是在springboot中已经不推荐使用JSP了,推荐使用模板引擎进行页面渲染,在本文中将整合thymeleaf模板引擎
修改pom文件,添加依赖
将以下依赖添加到pom文件中
<!-- thymeleaf支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
修改application.yml的配置
配置application.yml文件,注意每一项配置的键和值之间有空格,不同级别的配置需要缩进
spring:
thymeleaf:
encoding: utf-8
suffix: .html
cache: false #开发过程中关闭缓存
mode: LEGACYHTML5 #thymeleaf语法检查过于严格,通过此项关闭
在controller中添加测试方法
/**
* 前往thymeleaf模板引擎渲染的主页,模板页面放在resources/templates下
* 请求地址为http://localhost:8080/
*/
@GetMapping("/")
public String testThymeleaf(Model model){
//设置两个参数传入到模板引擎
//第一个参数是键 第二个参数是值
model.addAttribute("str","字符串");
model.addAttribute("bool",false);
model.addAttribute("list", Arrays.asList(1,2,3,4,5));
//指定模板为templates文件夹下的index.html
return "index.html";
}
添加模板页面
在resources/templates下添加模板页面
页面代码如下
<!DOCTYPE html>
<html lang="zh-Hans" xmlns:th="http://www.thymeleaf.org">
<head>
<title>thymeleaf-测试</title>
</head>
<body>
<h1>thymeleaf-测试</h1>
<h2>controller传入字符串参数:</h2>
<!-- 通过类似JSP的EL表达式把值取出来 -->
<div th:text="${str}"></div>
<h2>thymeleaf条件判断:</h2>
bool的值为:
<span th:if="${bool}">true</span>
<span th:unless="${bool}">false</span>
<h2>thymeleaf循环遍历list集合:</h2>
<!-- 循环遍历list集合 -->
<ul>
<li th:each="temp : ${list}" th:text="${temp}"></li>
</ul>
</body>
</html>
启动程序在浏览器中访问 http://localhost:8080/ ,界面如下