Thymeleaf入門(一)——入門與基本概述

 

1、概述

 

 

  1.是什麼html

 

    簡單說, Thymeleaf 是一個跟 Velocity、FreeMarker 相似的模板引擎,它能夠徹底替代 JSP 。前端

 

  2.featurejava

 

    1.Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可讓美工在瀏覽器查看頁面的靜態效果,也可讓程序員在服務器查看帶數據的動態頁面效果。這是因爲它支持 html 原型,而後在 html 標籤裏增長額外的屬性來達到模板+數據的展現方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,因此 thymeleaf 的模板能夠靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。程序員

       2.Thymeleaf 開箱即用的特性。它提供標準和spring標準兩種方言,能夠直接套用模板實現JSTL、 OGNL表達式效果,避免天天套模板、該jstl、改標籤的困擾。同時開發人員也能夠擴展和建立自定義的方言。
       3. Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,能夠快速的實現表單綁定、屬性編輯器、國際化等功能。

 

  3.文檔web

 

    官方教程http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#what-is-thymeleafspring

 

    推薦教程http://blog.didispace.com/springbootweb/express

 

         http://blog.csdn.net/u012706811/article/details/52185345後端

 

 2、HelloWorld

1.引入依賴瀏覽器

    springboot直接引入:緩存

 

1   <dependency>
2       <groupId>org.springframework.boot</groupId>
3       <artifactId>spring-boot-starter-thymeleaf</artifactId>
4     </dependency>

 

非springboot項目使用以下依賴:

 

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>2.1.4</version>
</dependency>

 

  默認的模板映射路徑是:src/main/resources/templates,

  springboot1.4以後,可使用thymeleaf3來提升效率,而且解決標籤閉合問題,配置方式

 

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!-- set thymeleaf version -->
    <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
    <!--set java version-->
    <java.version>1.8</java.version>
  </properties>

 

以前的model/modelMap/modelAndView等頁面數據傳遞參考以前隨筆:點擊查看

    快速回顧:

 

package com.learndemo.controller;

import java.util.HashMap;
import java.util.Map;

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

@Controller
@RequestMapping(value = "/return")
public class LearnReturnType {

    /**
     * Model自己不能設置頁面跳轉的url地址別名或者物理跳轉地址,那麼咱們能夠經過控制器方法的返回值來設置跳轉url
     * 地址別名或者物理跳轉地址
     * 
     * @param model
     *            一個接口, 其實現類爲ExtendedModelMap,繼承了ModelMap類
     * @return 跳轉url地址別名或者物理跳轉地址
     */
    @RequestMapping(value = "/index1")
    public String index1(Model model) {
        model.addAttribute("result", "後臺返回index1");
        return "result";
    }

    /**
     * ModelMap對象主要用於傳遞控制方法處理數據到結果頁面,相似於request對象的setAttribute方法的做用。 用法等同於Model
     * 
     * @param model
     * @return 跳轉url地址別名或者物理跳轉地址
     */

    @RequestMapping(value = "/index2")
    public String index2(ModelMap model) {
        model.addAttribute("result", "後臺返回index2");
        return "result";
    }

    /**
     * ModelAndView主要有兩個做用 設置轉向地址和傳遞控制方法處理結果數據到結果頁面
     * @return 返回一個模板視圖對象
     */
    @RequestMapping(value = "/index3")
    public ModelAndView index3() {
        ModelAndView mv = new ModelAndView("result");
        // ModelAndView mv = new ModelAndView();
        // mv.setViewName("result");
        mv.addObject("result", "後臺返回index3");
        return mv;
    }

    /**
     * map用來存儲遞控制方法處理結果數據,經過ModelAndView方法返回。
     * 固然Model,ModelMap也能夠經過這種方法返回
     * @return 返回一個模板視圖對象
     */
    @RequestMapping(value = "/index4")
    public ModelAndView index4() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("result", "後臺返回index4");
        return new ModelAndView("result", map);
    }
}

model/modelMap/modelAndView

 

  2.配置thymeleaf視圖解析器

    這點與springMVC是相相似的:

 

#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#開發時關閉緩存,否則無法看到實時頁面
spring.thymeleaf.cache=false
#thymeleaf end

 

實際項目中可能會有不太嚴格的HTML格式,此時設置mode=HTML5將會對非嚴格的報錯,能夠參考如下配置:

 

spring.thymeleaf.mode=LEGACYHTML5

 

你可能會發如今默認配置下,thymeleaf對.html的內容要求很嚴格,好比<meta charset="UTF-8" />,
若是少最後的標籤封閉符號/,就會報錯而轉到錯誤頁。也好比你在使用Vue.js這樣的庫,而後有<div v-cloak></div>這樣的html代碼,
也會被thymeleaf認爲不符合要求而拋出錯誤。

所以,建議增長下面這段:

spring.thymeleaf.mode = LEGACYHTML5
spring.thymeleaf.mode的默認值是HTML5,實際上是一個很嚴格的檢查,改成LEGACYHTML5能夠獲得一個可能更友好親切的格式要求。

須要注意的是,LEGACYHTML5須要搭配一個額外的庫NekoHTML纔可用。

<dependency>  
       <groupId>net.sourceforge.nekohtml</groupId>  
       <artifactId>nekohtml</artifactId>  
       <version>1.9.22</version>  
</dependency>  


最後重啓項目就能夠感覺到不那麼嚴格的thymeleaf了。

這樣,須要的配置項以下:

 

# 一項是非嚴格的HTML檢查,一項是禁用緩存來獲取實時頁面數據,其餘採用默認項便可
  thymeleaf:
    mode: LEGACYHTML5
    cache: false

 

  // 完整配置項參考類ThymeleafProperties

  3。編寫控制器

 

/**
 * 測試demo的controller
 *
 * @author zcc ON 2018/2/8
 **/
@Controller
public class HelloController {
    private static final Logger log = LoggerFactory.getLogger(HelloController.class);

    @GetMapping(value = "/hello")
    public String hello(Model model) {
        String name = "jiangbei";
        model.addAttribute("name", name);
        return "hello";
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

4.編寫模板html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
    <!--/*@thymesVar id="name" type="java.lang.String"*/-->
    <p th:text="'Hello!, ' + ${name} + '!'">3333</p>
</body>
</html>

其中,註釋是經過alt+enter進行自動生成的,便於IDEA補全,若是不加,IDEA將會報錯cannot reslove,

  固然也能夠經過以下方式解決,解決以前推薦在maven項目中reimport一下!(聽說新版本的IDEA中已經修復此問題,待更新至2017.3之後)

5.測試

 3、基礎語法

  1.建立HTML

    由上文也能夠知道須要在html中添加:

 

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

 

    這樣,下文才能正確使用th:*形式的標籤!

  2.獲取變量值${...}

    經過${…}進行取值,這點和ONGL表達式語法一致!

 

  <!--/*@thymesVar id="name" type="java.lang.String"*/-->
    <p th:text="'Hello!, ' + ${name} + '!'">3333</p>

 

選擇變量表達式*{...}

 

<div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> 
    <p>Nationality: <span th:text={nationality}">Saturn</span>.</p>
</div> 
等價於
<div>
    <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p> 
    <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p> 
    <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

 

    至於p裏面的原有的值只是爲了給前端開發時作展現用的.這樣的話很好的作到了先後端分離。

    這也是Thymeleaf很是好的一個特性:在無網絡的狀況下也能運行,也就是徹底能夠前端先寫出頁面,模擬數據展示效果,後端人員再拿此模板修改便可!

  3.連接表達式: @{…} 

    用來配合link src href使用的語法,相似的標籤有:th:hrefth:src

 

<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) --> 

<a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a> <!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->

<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

<a href="details.html" th:href="@{order/{orderId}/details(orderId=${o.id})}">Content路徑,默認訪問static下的order文件夾</a>

 

4.文本替換

 

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

 

或者下面的表達方式:(只能包含表達式變量,而不能有條件判斷等!)

 

<span th:text="|Welcome to our application, ${user.name}!|">

 

  5.運算符

    數學運算

  • 二元操做:+, - , * , / , %
  • 一元操做: - (負)

    邏輯運算

  • 一元 : and or
  • 二元 : !,not

    比較運算(爲避免轉義尷尬,可使用括號中的英文進行比較運算!)

  • 比較:> , < , >= , <= ( gt , lt , ge , le )
  • 等於:== , != ( eq , ne )

    條件運算

  • If-then: (if) ? (then)
  • If-then-else: (if) ? (then) : (else)
  • Default: (value) ?: (defaultvalue)

 

 

 

 

 

 

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

 6.條件

   if/unless

   使用th:if和th:unless屬性進行條件判斷,th:unless於th:if剛好相反,只有表達式中的條件不成立,纔會顯示其內容。

 

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

 

switch

 

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

 

  7.循環

     經過th:each

 

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
    <!-- 不存在則忽略,顯示hello null!(能夠經過默認值進行設置)-->
    <p th:text="'Hello ' + (${name}?:'admin')">3333</p>
    <table>
        <tr>
            <th>ID</th>
            <th>NAME</th>
            <th>AGE</th>
        </tr>
        <tr th:each="emp : ${empList}">
            <td th:text="${emp.id}">1</td>
            <td th:text="${emp.name}">海</td>
            <td th:text="${emp.age}">18</td>
        </tr>
    </table>
</body>
</html>

 

 

 

 

 

後臺:

 

@GetMapping(value = "/hello")
    public String hello(Model model) {
        List<Emp> empList = new ArrayList<>();
        empList.add(new Emp(1, "校長", 24));
        empList.add(new Emp(2, "書記", 28));
        empList.add(new Emp(3, "小海", 25));
        model.addAttribute("empList", empList);
        return "hello";
    }

HelloController

 

  更多循環深刻,iterStat等示例,參考http://blog.csdn.net/sun_jy2011/article/details/40710429

  8.內置對象Utilites

    通常不推薦在前端進行這些處理,前端頁面以減小邏輯爲宜

 

#dates :

utility methods for java.util.Date objects: formatting, component extraction, etc. #calendars : analogous to #dates , but for java.util.Calendar objects.

#numbers :
utility methods for formatting numeric objects.

#strings : 
utility methods for String objects: contains, startsWith, prepending/appending, etc. #objects : utility methods for objects in general.

#bools : 
utility methods for boolean evaluation. #arrays : utility methods for arrays.

#lists :
utility methods for lists.

#sets : 
utility methods for sets.

#maps : 
utility methods for maps.

#aggregates : 
utility methods for creating aggregates on arrays or collections.

#messages : 
utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{...} syntax.

#ids : 
utility methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

 

經常使用示例:

/*
 * Format date with the specified pattern
 * Also works with arrays, lists or sets
 */
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}

/*
 * Create a date (java.util.Date) object for the current date and time
 */
${#dates.createNow()}

/*
 * Create a date (java.util.Date) object for the current date (time set to 00:00)
 */
${#dates.createToday()}

#dates
/*
 * Check whether a String is empty (or null). Performs a trim() operation before check
 * Also works with arrays, lists or sets
 */
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}

/*
 * Check whether a String starts or ends with a fragment
 * Also works with arrays, lists or sets
 */
${#strings.startsWith(name,'Don')}                  // also array*, list* and set*
${#strings.endsWith(name,endingFragment)}           // also array*, list* and set*

/*
 * Compute length
 * Also works with arrays, lists or sets
 */
${#strings.length(str)}

/*
 * Null-safe comparison and concatenation
 */
${#strings.equals(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)}

/*
 * Random
 */
${#strings.randomAlphanumeric(count)}

String

完整參考點擊查看

 

4、經常使用標籤

 

 

 

 

 

 

   // 相似於th:object和th:field等進行表單參數綁定仍是頗有用的!使用與注意事項,參見:這裏

 

   參考博文http://www.javashuo.com/article/p-snzoewsh-ho.html

相關文章
相關標籤/搜索