1. 程式人生 > 其它 >springboot+模版引擎(七)

springboot+模版引擎(七)

1.springboot整合freemarker

略。對後端開發來說,成本比thymeleaf高。

2.springboot整合thymeleaf

好處:前後端不分離,但是成本低,上手起來簡單,可以專注後端開發

如何整合?

1.引入依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.配置application.property

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#關閉快取,即使重新整理。線上改為true
spring.thymeleaf.cache=false

3.在靜態資源目錄resource下新增thymeleaf資料夾,在該資料夾下新增index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
Thymeleaf模板引擎
<h1 th:text="${name}">hello world~~~~~~~</h1>
</body>
</html>

  

4.在thymeleaf資料夾下新增center資料夾,在該資料夾下新增center.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
Thymeleaf模板引擎
<h1>center page</h1>
</body>
</html>

  

5.新增ThymeleafController類,訪問模版

@Controller
@RequestMapping("th")
public class ThymeleafController {

	@RequestMapping("/index")
    public String index(ModelMap map) {
        map.addAttribute("name", "thymeleaf-anson2021b");
        return "thymeleaf/index";
    }
	
	@RequestMapping("center")
    public String center() {
        return "thymeleaf/center/center";
    }
}

  

6.啟動服務,通過瀏覽器訪問

127.0.0.1:8080/th/index或者直接訪問html,127.0.0.1:8080/th/index.html

127.0.0.1:8080/th/center或者直接訪問html,127.0.0.1:8080/th/center.html

獲得html頁內容,並且可見index模版獲取name的內容為thymeleaf-anson2021b