什么是Thymeleaf
Thymeleaf的優(yōu)點(diǎn)是它是基于HTML的,即使視圖沒有渲染成功,也是一個(gè)標(biāo)準(zhǔn)的HTML頁面。
前身方法
前期技術(shù)都是JSP,JSP的優(yōu)點(diǎn)是它是Java EE容器的一部分,幾乎所有Java EE服務(wù)器都支持JSP。缺點(diǎn)就是它在視圖表現(xiàn)方面的功能很少,假如我們想迭代一個(gè)數(shù)組之類的,只能使用<% %>來包括Java語句進(jìn)行。雖然有標(biāo)準(zhǔn)標(biāo)簽庫(JSTL)的補(bǔ)足,但是使用仍然不太方便。另外JSP只能在JavaEE容器中使用,如果我們希望渲染電子郵件之類的,JSP就無能為力了。
配置引入方法
1、添加依賴
<!--thymeleaf模板引擎依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、Controller寫法
@Controller
public class IndexController {
//注入一個(gè)student類對象,被spring容器托管---bean
@Resource
private Student student;
// @RequestMapping(value="/index",method = RequestMethod.GET)
@GetMapping("index")
public String index(ModelMap map){
student.setAge(20);
student.setName("Tom");
student.setMale("male");
student.setStudentNo("2018");
//將模型加入視圖
map.addAttribute("student",student);
return "index";//返回值就是頁面名稱
}
}
3、HTML寫法
頂部添加
<html xmlns:th="http://www.thymeleaf.org">
配合WebJars
1、添加依賴
<!--引用bootstrap-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7-1</version>
</dependency>
2、網(wǎng)頁代碼
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主頁</title>
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div class="alert alert-success">
<p th:text="${student.name}"></p>
<p th:text="${student.age}"></p>
<p th:text="${student.male}"></p>
</div>
</div>
</body>
</html>
3、Controller代碼
import javax.annotation.Resource;
/**
* Created by lenovo on 2018/9/6.
*/
@Controller
public class IndexController {
//注入一個(gè)student類對象,被spring容器托管---bean
@Resource
private Student student;
// @RequestMapping(value="/index",method = RequestMethod.GET)
@GetMapping("index")
public String index(ModelMap map){
student.setAge(20);
student.setName("Tom");
student.setMale("male");
student.setStudentNo("2018");
//將模型加入視圖
map.addAttribute("student",student);
return "index";//返回值就是頁面名稱
}
}
Thymeleaf引擎配合WebJars效果圖初樣

效果圖.png