前言
- 由于springboot首先是以jar包的方式来存在(可能不太恰当),不是war,而且,用的还是嵌入式的Tomcat,所以,springboot是不支持jsp的,所以当后台查出来我们想要的数据时,并不能使用之前的jsp来实现交互,所以我们得尝试着改变了!
- 耳熟的模板引擎:jsp,freemarker,thymeleaf…
- 模板引擎的思想
如何使用
引入thymeleaf 的三个网址
- Thymeleaf官网: https://www.thymeleaf.org/
- Github:https://github.com/thymeleaf/thymeleaf
- spring官方文档:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#using-boot-starter
新建项目导入从上面官网找到的依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
在templates目录下新建html页面
编写TestController类
package com.buba.springbootplayback.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//在templates下的所有页面.只能通过controller来跳转
//这个需要模板引擎的支持 thymeleaf
@Controller
public class TestController {
@RequestMapping("/test")
public String test(){
return "test";
}
}
访问测试
小结
- 只要需要使用thymeleaf,导入对应的依赖就可以了
- 再将html页面放在templates目录下即可
因为:public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";
- 现在我们的controller和html页面已经有了联系,下面看一下最基本的语法
基本语法
配置命名空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
编写controlelr
package com.buba.springbootplayback.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
//在templates下的所有页面.只能通过controller来跳转
//这个需要模板引擎的支持 thymeleaf
@Controller
public class TestController {
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("msg","消息");
return "test";
}
}
编写html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--所有的HTML元素都可以被thymeleaf接管, th:元素名-->
<html th:text="${msg}"></html>
</body>
</html>
启动测试
- 可以看到HTML通过thymeleaf成功的取到了controller返回的数据!
常用的一些语法(我这里只有遍历的…)
- 遍历取值
@RequestMapping("/test") public String test(Model model){ model.addAttribute("users", Arrays.asList("123","456")); return "test"; }
<h3 th:each="user:${users}" th:text="${user}"></h3> <!--行内写法 不常用但是得了解--> <!--<h3 th:each="user:${users}">[[ ${user} ]]</h3>-->