1. 程式人生 > >Thymeleaf 模板 在spring boot 中的引用和應用

Thymeleaf 模板 在spring boot 中的引用和應用

end text www. bean template har ica ngs sta

Thymeleaf是一個java類庫,他是一個xml/xhtml/html5的模板引擎和Struts框架的freemarker模板類似,可以作為mvc的web應用的view層。
Thymeleaf還提供了額外的模塊與Spring MVC集成,所以我們可以使用Thymeleaf完全替代jsp。
spring Boot
通過org.springframework.boot.autoconfigure.thymeleaf包對Thymeleaf進行了自動配置。
通過ThymeleafAutoConfiguration類對集成所需要的bean進行自動配置。包括templateResolver,templateEngine,thymeleafViewResolver的配置。

1.pom.xml中添加

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

自動下載thymeleaf的jar包,然後update Project.

2.application.properties中添加thymeleaf配置文件

#Thymeleaf
spring.thymeleaf.prefix
=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 # ;charset=<encoding> is added #spring.thymeleaf.content-type=text/html #set to false for hot refresh spring.thymeleaf.cache=false

3.之後寫一個測試

a.在項目目錄下找src/main/resources/templates新建一個dome.html測試網頁,註意要在頭部引用

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"  
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">  ,不然找不到網頁。
<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"  
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">  
    <head>  
        <title th:text="${title}"></title>  
    </head>  
    <body>    
        <p th:text="${gr}"></p>  
    </body>  
</html>  

b.寫測試controller層Thymeleaf.class類

package com.hxzy.myblog.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Thymeleaf {
     @RequestMapping("/hi")
     public String helloHtml(Model model){ 
         model.addAttribute("title","Thymeleaf");
         model.addAttribute("gr","大家好");
         return "dome";
     }
}

4.總結:

1.註意html中標簽必須嚴格閉合

2.html中一對標簽中使用thymeleaf,用th:text="${title}",title就加在標簽內,如

<title th:text="${title}"></title> 。

Thymeleaf 模板 在spring boot 中的引用和應用