天天看點

Springboot內建Thymeleaf開發測試

  1. 第一步:在Maven中引入Thymeleaf的依賴,加入以下依賴配置即可:
<dependency>
 			<groupId>org.springframework.boot</groupId>
 			<artifactId>spring-boot-starter-thymeleaf</artifactId>
 		</dependency>
           
  1. 第二步:在Spring boot的核心配置檔案application.properties中對Thymeleaf進行配置:

    #開發階段,建議關閉thymeleaf的緩存

    spring.thymeleaf.cache=false

    #使用遺留的html5以去掉對html标簽的校驗

    spring.thymeleaf.mode=LEGACYHTML5

    在使用springboot的過程中,如果使用thymeleaf作為模闆檔案,則要求HTML格式必須為嚴格的html5格式,必須有結束标簽,否則會報錯;如果不想對标簽進行嚴格的驗證,使用spring.thymeleaf.mode=LEGACYHTML5去掉驗證。去掉驗證,則需要引入如下依賴,否則會報錯(Springboot2.0+版本可不引入以下依賴):

<dependency>
		<groupId>net.sourceforge.nekohtml</groupId>
		<artifactId>nekohtml</artifactId>
	</dependency>
	<dependency>
		<groupId>org.unbescape</groupId>
		<artifactId>unbescape</artifactId>
		<version>1.1.5RELEASE</version>
	</dependency>
           

NekoHTML是一個Java語言的HTML掃描器和标簽補全器,這個解析器能夠掃描HTML檔案并“修正”HTML文檔中的常見錯誤。

NekoHTML能增補确實的父元素,自動用結束标簽關閉相應的元素,修改不比對的内嵌标簽等;

3. 第三步:寫一個Controller去映射到模闆頁面(和SpringMVC基本一緻),比如:

@RequestMapping("/index")
 	public String index(Model model){
		model.addAttribute("data","恭喜,Spring boot 內建Thymeleaf成功!");
		//return 中就是頁面的名字(不帶html字尾)
		return "index";
	}
           
  • 第四步:在src/main/resources的templates下建立一個index.html頁面用于展示資料:

    HTML頁面的元素中加入以下屬性:

<html xmlns:th="http://www.thymeleaf.org">
           

HTML頁面

<!DOCTYPE html>
	<html xmlns:th="http://www.thymeleaf.org">
		<head>
			<meta charset="UTF-8"/>
			<title>Springboot內建Thymeleaf</title>
		</head>
		<body>
			<p th:text="${data}">Springboot內建Thymeleaf</p>
		</body>
	</html>
           
  • Springboot使用Thymeleaf作為視圖展示,約定将模闆檔案放置在src/main/resource/templates目錄下,靜态資源放置在src/main/resource/static目錄下

繼續閱讀