1. 程式人生 > >spring-boot--使用thymeleaf模板

spring-boot--使用thymeleaf模板

轉:http://jisonami.iteye.com/blog/2301387,http://412887952-qq-com.iteye.com/blog/2292402

整體步驟:
(1)            在pom.xml中引入thymeleaf;
(2)            如何關閉thymeleaf快取
(3)            編寫模板檔案.html

Spring Boot預設就是使用thymeleaf模板引擎的,所以只需要在pom.xml加入依賴即可:

<dependency>
         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Thymeleaf快取在開發過程中,肯定是不行的,那麼就要在開發的時候把快取關閉,只需要在application.properties進行配置即可:

########################################################
###THYMELEAF (ThymeleafAutoConfiguration)
########################################################
#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

編寫模板檔案src/main/resouces/templates/helloHtml.html
<!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>Hello World!</title>
    </head>
    <body>
        <h1 th:inline="text">Hello.v.2</h1>
        <p th:text="${hello}"></p>
    </body>
</html>
編寫訪問路徑(com.kfit.test.web.TemplateController):
package com.kfit.test.web;

import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

 

/**

 * 模板測試.

 * @author Administrator

 *

 */

@Controller

publicclass TemplateController {
    /**

     * 返回html模板.

     */

    @RequestMapping("/helloHtml")
    public String helloHtml(Map<String,Object> map){

       map.put("hello","from TemplateController.helloHtml");
       return"/helloHtml";
    }
}

啟動應用,輸入地址:http://127.0.0.1:8080/helloHtml 會輸出:

Hello.v.2

from TemplateController.helloHtml

使用freemarker
使用freemarker也很簡單,
在pom.xml加入freemarker的依賴:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
剩下的編碼部分都是一樣的,說下application.properties檔案:
########################################################
###FREEMARKER (FreeMarkerAutoConfiguration)
########################################################
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
#spring.freemarker.suffix=.ftl
#spring.freemarker.template-loader-path=classpath:/templates/#comma-separatedlist
#spring.freemarker.view-names= #whitelistofviewnamesthatcanberesolved
com.kfit.test.web.TemplateController:
/**
  * 返回html模板.
  */

    @RequestMapping("/helloFtl")
    public String helloFtl(Map<String,Object> map){
       map.put("hello","from TemplateController.helloFtl");
       return"/helloFtl";
    }

Hello.v.2

from TemplateController.helloFtl

thymeleaffreemarker是可以共存的。

------------------------------------------------------------------------------------------------------------------------------------------------

本文記錄一下幾點: 
一、資原始檔的約定目錄結構 
二、Maven配置 
三、開發時修改thymeleaf模板自動重新載入配置 
四、thymeleaf常用基礎知識點

一、資原始檔的約定目錄結構 

Maven的資原始檔目錄:/src/java/resources 
spring-boot專案靜態檔案目錄:/src/java/resources/static 
spring-boot專案模板檔案目錄:/src/java/resources/templates 
spring-boot靜態首頁的支援,即index.html放在以下目錄結構會直接對映到應用的根目錄下:

classpath:/META-INF/resources/index.html  
classpath:/resources/index.html  
classpath:/static/index.html  
calsspath:/public/index.html  

由於使用thymeleaf的html5模板,所以我將index.html模板檔案直接放到了/src/java/resources/templates目錄下。然而這個目錄並不是首頁檔案的預設目錄,所以我們需要手動將應用根路徑對映到/src/java/resources/templates/index.html下。這個在spring-mvc的Controller下對映一下就可以了。

@RequestMapping("/")  
    public String index(){  
        return "index";  
  } 
在spring-boot下,預設約定了Controller試圖跳轉中thymeleaf模板檔案的的字首prefix是”classpath:/templates/”,字尾suffix是”.html” 
這個在application.properties配置檔案中是可以修改的。 
如下配置可以修改試圖跳轉的字首和字尾
spring.thymeleaf.prefix: /templates/  
spring.thymeleaf.suffix: .html  

更過有關thymeleaf中的預設這是可以檢視org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties這個類的屬性 
二、Maven配置 
在pom.xml中加入如下依賴 
<dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-thymeleaf</artifactId>  
</dependency>

原來關於spring-boot-starter-web等的依賴就可以去掉了,因為spring-boot-starter-thymeleaf是包含這些依賴的。而關於jsp的依賴也可以去掉了,因為我們已經完全拋棄jsp了。 


三、開發時修改thymeleaf模板自動重新載入配置 
Spring-boot使用thymeleaf時預設是有快取的,即你把一個頁面程式碼改了不會重新整理頁面的效果,你必須重新執行spring-boot的main()方法才能看到頁面更改的效果。我們可以把thymeleaf的快取關掉,用於支援頁面修改後重新發布到spring-boot內嵌的tomcat中去。在application.properties配置檔案中加入以下配置。
# Allow Thymeleaf templates to be reloaded at dev time  
spring.thymeleaf.cache: false  
server.tomcat.access_log_enabled: true  
server.tomcat.basedir: target/tomcat 

四、thymeleaf常用基礎知識點 


1、在html頁面中引入thymeleaf名稱空間,即<html xmlns:th=http://www.thymeleaf.org></html>,此時在html模板檔案中動態的屬性使用th:名稱空間修飾 


2、引用靜態資原始檔,比如CSS和JS檔案,語法格式為“@{}”,如@{/js/blog/blog.js}會引入/static目錄下的/js/blog/blog.js檔案 


3、訪問spring-mvc中model的屬性,語法格式為“${}”,如${user.id}可以獲取model裡的user物件的id屬性 


4、迴圈,在html的標籤中,加入th:each=“value:${list}”形式的屬性,如<span th:each=”user:${users}”></span>可以迭代users的資料 


5、判斷,在html標籤中,加入th:if=”表示式”可以根據條件顯示html元素 
<span th:if="${not #lists.isEmpty(blog.publishTime)}"> 
<span id="publishtime" th:text="${#dates.format(blog.publishTime, 'yyyy-MM-dd HH:mm:ss')}"></span> 
</span> 
以上程式碼表示若blog.publishTime時間不為空,則顯示時間 


6、時間的格式化, 
${#dates.format(blog.publishTime,'yyyy-MM-dd HH:mm:ss')} 
表示將時間格式化為”yyyy-MM-dd HH:mm:ss”格式化寫法與Java格式化Date的寫法是一致的。 


7、字串拼接,有兩種形式 
比如拼接這樣一個URL:/blog/delete/{blogId} 
第一種:th:href="'/blog/delete/' + ${blog.id }" 
第二種:th:href="${'/blog/delete/' + blog.id }"