1. 程式人生 > >SpringBoot模板引擎及原理

SpringBoot模板引擎及原理

一、模板引擎的思想:


    模板是為了將顯示與資料分離,模板技術多種多樣,但其本質都是將模板檔案和資料通過模板引擎生成最終的HTML程式碼。
  

二、SpringBoot模板引擎:


 SpringBoot推薦的模板引擎是Thymeleaf——>語法簡單,功能強大。
 1)、引入thymeleaf的starter啟動器。

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

        <!-- 預設版本號在parent的dependents中配置,如果要替換其中的版本,設定如下 -->
	<properties>
		<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
                <!-- 佈局功能的支援程式 thymeleaf3主程式,適配layout2以上版本 -->
		<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
	</properties>

  2)、檢視thymeleaf的預設配置:進入ThymeleafAutoConfigurationThymeleafProperties配置檔案中,如下:

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
    private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    //只要我們吧HTML頁面放在classpath:/templates/下就能夠自動渲染
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";

  3)、測試:建立controller如下:同時在templates資料夾下建立suceess.html與返回值相同。啟動後輸入:http://localhost:8080/success便可跳轉到success.html頁面。

@Controller
public class success {
    @RequestMapping("/success")
    public String success(){
        return "success";
    }
}

三、thymeleaf使用


 1)、匯入thymeleaf的名稱空間:就會具有thymeleaf的語法提示,不匯入也可以,只是麼有語法提示了。

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

  2)、寫一個簡單的demo上個手,如下controller層,給返回的頁面新增資料,如下:

@Controller
public class success {
    @RequestMapping("/success")
    public String success(Map<String,String> map){
        map.put("hello","你好");
        return "success";
    }
}

  3)、開啟我們的靜態頁面success.html,根據thymeleaf模板引擎語法,獲取hello的值,如下:

<body>
    <h1>成功</h1>
    <div th:text="${hello}">
        這是成功頁面
    </div>
</body>

  4)、需要注意的是:當hello有值時,顯示hello獲取到的值,如果單獨只訪問success.html時,只顯示前端頁面的內容 “這是成功頁面” 能夠非常友好的結合前後端進行程式設計。
    

四、thymeleaf語法規則:


 1)、th:text:改變當前元素裡面的文字內容。語法文件:https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.pdf
          th:任意html屬性:可以替換原生的HTML的元素。
          
   2)、表示式語法:行裡表示式:[[xx]]—相當於th:text , [(xx)]—相當於th:utext

● Simple expressions:(表示式語法)
    ○ Variable Expressions: ${...}:獲取變數值,底層時OGNL;
        1)、獲取物件的屬性、呼叫方法;
        2)、使用內建的基本物件;#location...
        3)、內建的一些工具物件;#strings...
    ○ Selection Variable Expressions: *{...}:選擇表示式,與${}的功能一樣,有一個不同,可以參考文件。
    ○ Message Expressions: #{...}:用來獲取國際化資訊
    ○ Link URL Expressions: @{...}:用來定義URL連線
    ○ Fragment Expressions: ~{...}:片段引入表示式
● Literals(字面量)
    ○ Text literals: 'one text' , 'Another one!' ,…
    ○ Number literals: 0 , 34 , 3.0 , 12.3 ,…
    ○ Boolean literals: true , false
    ○ Null literal: null
    ○ Literal tokens: one , sometext , main ,…
● Text operations:(文字操作)
    ○ String concatenation: +
    ○ Literal substitutions: |The name is ${name}|
● Arithmetic operations:(數學運算)
    ○ Binary operators: + , - , * , / , %
    ○ Minus sign (unary operator): -
● Boolean operations:(布林運算)
    ○ Binary operators: and , or
    ○ Boolean negation (unary operator): ! , not
● Comparisons and equality:(比較運算)
    ○ Comparators: > , < , >= , <= ( gt , lt , ge , le )
    ○ Equality operators: == , != ( eq , ne )
● Conditional operators:(條件運算)
    ○ If-then: (if) ? (then)
    ○ If-then-else: (if) ? (then) : (else)
    ○ Default: (value) ?: (defaultvalue)
    ○ Special tokens:
    ○ Page 17 of 106
● No-Operation: _:(特殊操作)

   3)、公共頁面抽取

<!--抽取公共片段-->
<div th:fragment="copy">
     2011 The Good Thymes Virtual Grocery
</div>

<!--引入公共片段: ~{templatename::fragmentname} 片段 ~{templatename::selector} 選擇器-->
<div th:insert="~{footer :: copy}"></div>
<-- or -->
<div th:insert="footer :: copy"></div>

  三種引入功能片段的區別:
 ▶ th:insert:將公共片段整個插入到宣告引入的元素中。
 ▶ th:replace:將宣告引入的元素替換成公共片段。
 ▶ th:include:將被引入的片段的內容包含進這個標籤中。

<footer th:fragment="copy">
    2011 The Good Thymes Virtual Gro
</footer>

<!--引入方式-->
<div th:insert="footer :: copy"></di>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>

<!--效果-->
<div>
    <footer>
        2011 The Good Thymes Virtual Grocery
    </footer>
</div>

<footer>
    2011 The Good Thymes Virtual Grocery
</footer>

<div>
    2011 The Good Thymes Virtual Grocery
</div>

  4)、日期格式化:通過內建物件dates進行格式化。

<td th:text="${#dates.format(emp.birth,'yyyy-MM-dd')}"></td>

  5)、 通過PUT請求提交資料:
     ● SpringMVC中配置HiddenHttpMethodFilter,(SpringBoot自動配置好)。
     ● 頁面建立一個post表單。
     ● 建立一個input項,name="_method",值就是我們指定的方式。

    private String methodParam = "_method";
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest requestToUse = request;
        if("POST".equals(request.getMethod()) && request.getAttribute("javax.servlet.error.exception") == null) {
            //重點:獲取_method傳過來的值
            String paramValue = request.getParameter(this.methodParam);
            if(StringUtils.hasLength(paramValue)) {
                String method = paramValue.toUpperCase(Locale.ENGLISH);
                if(ALLOWED_METHODS.contains(method)) {
                    requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);
                }
            }
        }

        filterChain.doFilter((ServletRequest)requestToUse, response);
    }

頁面實際操作:

<input type="hidden" name="_method" value="put" th:if="${emp}!=null">