SpringBoot學習日誌之_DAY04整合前端模板thymeleaf
目錄
SpringBoot學習日誌之_DAY04整合前端模板thymeleaf
什麼是thymeleaf
之前一直是採用的JSP作爲前端模板,但是在springboot當中是推薦Thymeleaf當中前端模板的, Thymeleaf是一個跟 Velocity、FreeMarker 類似的模板引擎。
官方教程:http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#what-is-thymeleaf
創建項目
首先引入springboot對Thymeleaf的依賴
<!--界面模板引擎thymeleaf依賴 springboot推薦 代替JSP-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
然後在application.properties當中添加相關配置信息
#thymeleaf 配置信息
#取消緩存,修改HTML界面後立即生效,不然會讀取緩存,沒有變化
spring.thymeleaf.cache=false
#下面5個配置信息都是常用的默認的配置信息,如果不需要修改,不寫也行
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.servlet.content-type=text/html
創建controller以及在/templates/下創建一個index.html的文件
@Controller
public class ThymeleafController {
@GetMapping("/index")
public String show(Model model){
model.addAttribute("username", "hjljy");
model.addAttribute("success", "成功顯示相關信息");
return "index";
}
@GetMapping("/index1")
public String show1(Model model){
return "index1";
}
}
index.html 添加<html xmlns:th="http://www.thymeleaf.org"> 通過th進行取值
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>網站名稱</title>
</head>
<body>
<p th:text="${username}"> </p>
<p th:text="${success}"> </p>
</body>
</html>
index1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
success thymeleaf
</body>
</html>
進行測試
分別輸入:localhost:8080/index localhost:8080/index1查看效果