04.Spring Boot 實戰~Thymeleaf語法講解

04.Spring Boot 實戰~Thymeleaf語法講解

本文是上一篇文章的後續,詳情點擊該鏈接

字符串與變量輸出操作

在這裏插入圖片描述

@Controller
public class MyController {

    @RequestMapping("/show")
    public String showPage(Model model){
        model.addAttribute("msg","hello Thymeleaf");
        model.addAttribute("val","save");
        return "index";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <!--  th:text  在頁面中輸出值 EL表達式  -->
        <span th:text="${msg}"></span><br/>
        <!--   th:value 可以將一個值放入到 input 標籤的 value 中   -->
        <!--/*@thymesVar id="val" type="ch"*/-->
        <input type="button" th:value="${val}"><br/>
    </body>
</html>

在這裏插入圖片描述

字符串操作

       Thymeleaf 提供了一些內置對象,內置對象可直接在模板中使用。這些對象是以#引用的。

使用內置對象的語法

引用內置對象需要使用#
大部分內置對象的名稱都以 s 結尾。如:strings、numbers、dates
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h2>統一都是同一個字符串,當前傳過來的值是: hello Thymeleaf</h2>
        <!--  th:text  在頁面中輸出值  -->
        <span th:text="${msg}"></span><br/>
         th:value 可以將一個值放入到 input 標籤的 value 中<br/>
        <!--/*@thymesVar id="val" type="ch"*/-->
        <input type="button" th:value="${val}"><hr/>

        <!--/*@thymesVar id="key" type=""*/-->
        <!--   這裏直接就是EL表達式,裏面的Key不需要重複${}   -->
        判斷當前字符串是否爲空<br/>
        <span th:text="${#strings.isEmpty(msg)}"></span><hr/>

        判斷字符串是否包含指定的子串,如果包含返回 true,否則返回 false <br/>
        <span th:text="${#strings.contains(msg,'T')}"></span><hr/>

        判斷當前字符串是否以子串開頭,如果是返回 true,否則返回 false  <br/>
        <span th:text="${#strings.startsWith(msg,'t')}"></span><hr/>

        判斷當前字符串是否以子串結尾,如果是返回 true,否則返回 false<br/>
        <span th:text="${#strings.endsWith(msg,'f')}"></span><hr/>

        返回字符串的長度<br/>
        <span th:text="${#strings.length(msg)}"></span><hr/>

        查找子串的位置,並返回該子串的下標,如果沒找到則返回-1<br/>
        <span th:text="${#strings.indexOf(msg,'l')}"></span><hr/>

        截取子串,用法與 jdkString 類下 SubString 方法相同<br/>
        <span th:text="${#strings.substring(msg,2)}"></span><br/>
        <span th:text="${#strings.substring(msg,2,5)}"></span><hr/>

        字符串轉大小寫<br/>
        <span th:text="${#strings.toUpperCase(msg)}"></span><br/>
        <span th:text="${#strings.toLowerCase(msg)}"></span><hr/>

    </body>
</html>

在這裏插入圖片描述

日期格式化處理

格式化日期,默認的以瀏覽器默認語言爲格式化標準

       ${#dates.format(key)}

按照自定義的格式做日期轉換

       ${#dates.format(key,'yyyy/MM/dd')}

       ${#dates.year(key)} ${#dates.month(key)} ${#dates.day(key)}

條件判斷

th:if

    @RequestMapping("/IfIndex")
    public String IfIndex(Model model){
        model.addAttribute("sex","男");
        //跳到HTML
        return "ifindex";
    }
    <body>
        <div>
            <span th:if="${sex} == 男">
                性別:男
            </span>
            <span th:if="${sex} == 女">
                性別:女
            </span>
        </div>
    </body>

在這裏插入圖片描述

th:switch/th:case

       th:switch / th:case 與 Java 中的 switch 語句等效,有條件地顯示匹配的內容。如果有 多個匹配結果只選擇第一個顯示。
        th:case="*"表示 Java 中 switch 的 default,即沒有 case 的值爲 true 時則顯示 th:case="*" 的內容。

    @RequestMapping("/IfIndex")
    public String IfIndex(Model model){
        //model.addAttribute("sex","男");
        model.addAttribute("score","80");
        //跳到HTML
        return "ifindex";
    }
        <div th:switch="${score}">
            <span th:case="100">特別優秀!</span>
            <span th:case="90">優秀</span>
            <span th:case="80">良好</span>
            <span th:case="60">及格</span>
        </div>

在這裏插入圖片描述

雖然沒有default,但是如果想要類似的效果,可以使用*

<span th:case="*">不及格</span>

迭代遍歷

th:each

       迭代器,用於循環迭代集合

代碼實現

實體類

public class User implements Serializable {
    private String name;
    private Integer age;
}// Get Set 就不再文章裏面寫了
    @RequestMapping("/ForEach")
    public String ForEach(Model model){
        List<User> list = new ArrayList<>();
        User user = new User("李明",20);
        User user1 = new User("劉剛",22);
        User user2 = new User("張倩",25);
        list.add(user); list.add(user1); list.add(user2);
        model.addAttribute("list",list);
        //跳到HTML
        return"forEach";
    }
for each使用
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <table border="1px">
            <tr>
                <th>姓名</th>
                <th>年齡</th>
            </tr>
            <tr th:each="user : ${list}">
                <td th:text="${user.getName()}"></td>
                <td th:text="${user.getAge()}"></td>
            </tr>
        </table>
    </body>
</html>

在這裏插入圖片描述

迭代器狀態變量

index 當前迭代器的索引從0開始
count 當前迭代對象的計數從1開始
size 被迭代對象的長度
odd/even 布爾值,當前循環是否是偶數/奇數 從 0 開始
first 布爾值,當前循環是否是第一條,是返回true,否則返回false
last 布爾值,當前循環是否是最後一條,是返回true,否則返回false

th:each 迭代 Map

        Map<String,User> map = new HashMap<>();
        map.put("精英",user);
        map.put("高級",user1);
        map.put("中級",user2);
        model.addAttribute("map",map);
        <table border="1px">
            <tr>
                <td align="center">Value</td>
            </tr>
            <tr th:each="map : ${map}">
                <td th:text="${map}"></td>
            </tr>
        </table>

在這裏插入圖片描述

我們發現,如果直接迭代的話,它就會自動變成Entry類型輸出到頁面

      <table border="1px">
           <tr>
               <td align="center">Value</td>
           </tr>
           <tr th:each="map : ${map}">
               <td th:text="${map.value}"></td>
           </tr>
       </table>

在這裏插入圖片描述

操作域對象

    @RequestMapping("/ObjReq")
    public String Obj(HttpServletRequest request){
        request.setAttribute("req","hello request");
        request.getSession().setAttribute("msg","hello session");
        request.getSession().getServletContext().setAttribute("app","application");
        return "objIndex";
    }
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <!--/*@thymesVar id="req" type="ch"*/-->
        <span th:text="${req}"></span> <br/>

        <span th:text="session.msg"></span><br/>

        <span th:text="${application.app}"></span>
    
    </body>
</html>

在這裏插入圖片描述

Thymeleaf的URL表達式

在 Thymeleaf 中 URL 表達式的語法格式爲@{}

絕對路徑
<a th:href="@{http://www.baidu.com}">絕對路徑</a>
相對路徑
<!--  相當於當前項目的根  -->
<a th:href="@{/show}">相對路徑</a>
<!-- 相對於服務器路徑的根   -->
<a th:href="@{~/project/resourcename}">相對於服務器的根</a>

在 URL 中傳遞參數

    @RequestMapping("/UrlShow")
    public String UrlShow(String id,String pwd){
        System.out.println(id + " " + pwd);
        return "objIndex";
    }
    <a th:href="@{/UrlShow?id=123456&pwd=654321}">嗯嗯</a>

在這裏插入圖片描述

restful 格式的 URL 中傳遞參數

關於restful格式,可以點擊這篇文章
  <a th:href="@{/UrlShow/{id}/{pwd}(id=123456,pwd=654321)}">restful</a>

在這裏插入圖片描述

  <a th:href="@{/UrlShow?id=123456&pwd=654321}">普通 URL 格式傳參</a> 
    
  <a th:href="@{/UrlShow(id=123456,pwd=654321)}">普通 URL 格式傳參</a> 
    
    <!--/*@thymesVar id="id" type="ch"*/-->
    <!--/*@thymesVar id="pwd" type=""*/-->
    <a th:href="@{'/UrlShow?id='+${id}+'&pwd='+${pwd}}">普通 URL 格式傳參 </a> 
    
    <a th:href="@{/UrlShow(id=${id},pwd=${pwd})}">普通 URL 格式傳參</a>
    
    <a th:href="@{/UrlShow/{id}(id=123456)}">restful 格式傳參</a> 
    
    <a th:href="@{/UrlShow/{id}/{pwd}(id=123456,pwd=654321)}">restful 格 式 傳 參 </a> 
    
    <a th:href="@{/UrlShow/{id}(id=123456,pwd=654321)}">restful 格式傳參</a> 
    
    <a th:href="@{/UrlShow/{id}(id=${id},pwd=${pwd})}">restful 格式傳參</a>

在配置文件中配置 Thymeleaf

修改路徑
spring.thymeleaf.prefix=classpath:/templates/alvin/

在這裏插入圖片描述

    @RequestMapping("/ShowPlus")
    public String ShowPlus(){
        return "ShowPlus";
    }

這個時候就可以直接跳到alvin下的ShowPlus

在這裏插入圖片描述

默認後綴

正是因爲有了這個,所以我們只需要寫名字,不寫後綴就可以跳到html那裏去

spring.thymeleaf.suffix=.html
配置視圖模板類型(HTML5)
spring.thymeleaf.mode=HTML
配置當前編碼格式(默認UTF-8)
spring.thymeleaf.encoding=UTF-8
響應類型
spring.thymeleaf.servlet.content-type=text/html 
配置頁面緩存
spring.thymeleaf.cache=false
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章