SpringBoot系列——Thymeleaf模板

  前言

  thymeleaf是springboot官方推薦使用的java模板引擎,在springboot的參考指南裏的第28.1.10 Template Engines中介紹並推薦使用thymeleaf,建議咱們應該避免使用jsp,jsp的本質是一個java的servlet類,jsp引擎將jsp的內容編譯成.class,"out.write"輸出到response再響應到瀏覽器,雖然java是一次編譯,處處運行,但也大大增長了服務器壓力,並且jsp將後臺java語言嵌入頁面,還要放入服務容器才能打開,先後端不分離,嚴重增長了前端工程師的開發工做、效率。javascript

  thymeleaf官網對thymeleaf的介紹:html

  Thymeleaf is a modern server-side Java template engine for both web and standalone environments.前端

  Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.java

  With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.react

 

  thymeleaf使用教程,騷操做:鼠標右鍵,翻譯成簡體中文再看。jquery

  thymeleaf使用th屬性賦予每一個標籤與後臺交互的能力,當html文件在本地直接用瀏覽器打開,瀏覽器引擎會忽略掉th屬性,並正常渲染頁面,當把html文件放到服務容器訪問,th屬性與後臺交互,獲取數據替換原先的內容,這樣前端工程師在編寫html頁面時,在本地開發,正常實現頁面邏輯效果便可,數據先寫死,當放到服務容器時數據從後臺獲取。git

 

  spring對thymeleaf的配置,來自springboot參考手冊,Common application properties:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#common-application-propertiesgithub

# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.cache=true # Whether to enable template caching.
spring.thymeleaf.check-template=true # Whether to check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Whether to check that the templates location exists.
spring.thymeleaf.enabled=true # Whether to enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.enable-spring-el-compiler=false # Enable the SpringEL compiler in SpringEL expressions.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names (patterns allowed) that should be excluded from resolution.
spring.thymeleaf.mode=HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.chunked-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be the only ones executed in CHUNKED mode when a max chunk size is set.
spring.thymeleaf.reactive.full-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be executed in FULL mode even if a max chunk size is set.
spring.thymeleaf.reactive.max-chunk-size=0B # Maximum size of data buffers used for writing to the response.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.render-hidden-markers-before-checkboxes=false # Whether hidden form inputs acting as markers for checkboxes should be rendered before the checkbox element itself.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.servlet.produce-partial-output-while-processing=true # Whether Thymeleaf should start writing partial output as soon as possible or buffer until template processing is finished.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names (patterns allowed) that can be resolved.

 

  使用

  maven引入依賴web

        <!--Thymeleaf模板依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

 

  項目結構spring

  thymeleaf默認,頁面跳轉默認路徑:src/main/resources/templates,靜態資源默認路徑:src/main/resources/static;

   

 

  yml配置文件

  咱們也能夠再配置文件中修改它:classpath:/view/

 

   controller頁面跳轉

  使用ModelAndView進行跳轉,將數據add進去

    @RequestMapping("/login.do")
    public ModelAndView login(User user){
        Result result=userService.login(user);
        ModelAndView mv=new ModelAndView();
        mv.addObject("newText","你好,Thymeleaf!");
        mv.addObject("gender","1");
        mv.addObject("userList",result.getData());
        if(result.getData()!=null) {
            mv.addObject("loginUser",result.getData());
        }
        mv.setViewName("index.html");
        return mv;
    }

 

  html頁面取值

  引入命名空間,避免校驗錯誤<html xmlns:th="http://www.thymeleaf.org">

<!DOCTYPE html>
<!--解決idea thymeleaf 表達式模板報紅波浪線-->
<!--suppress ALL -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>srpingboot</title>
</head>
<body>
    <!-- 屬性替換,其餘屬性同理 -->
    <h1 th:text="${newText}">Hello World</h1>
    <!--
        設置多個attr
        th:attr="id=${user.id},data-xxx=${user.xxx},data-yyy=${user.yyy}"

        片斷的使用、傳值和調用
        <div th:fragment="common(text1,text2)">
            ...
        </div>
        th:insert 是最簡單的:它只是插入指定的片斷做爲其主機標籤的主體。
        <div th:insert="base ::common(${text1},${text2})"></div>

        th:replace實際上用指定的片斷替換它的主機標籤。
        <div th:replace="base ::common(${text1},${text2})"></div>
    
     三目表達式:
     <h3 th:text="${loginUser != null} ? ${loginUser.username} : '請登陸'"></h3> 
--> <!-- if-else --> <h3 th:if="${loginUser} ne null" th:text="${loginUser.username}"></h3> <h3 th:unless="${loginUser} ne null">請登陸</h3> <!-- switch --> <div th:switch="${gender}"> <p th:case="'1'"></p> <p th:case="'0'"></p> <!-- th:case="*" 相似switch中的default --> <p th:case="*">其餘</p> </div> <!--
    each
    其中,iterStat參數爲狀態變量,經常使用的屬性有
    index 迭代下標,從0開始
    count 迭代下標,從1開始
    size 迭代元素的總量
    current 當前元素
   -->
    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>username</th>
                <th>password</th>
                <th>created</th>
                <th>description</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="user,iterStat : ${userList}">
                <td th:text="${user.id}"></td>
                <td th:text="${user.username}"></td>
                <td th:text="${user.password}"></td>
                <td th:text="${user.created}"></td>
                <td th:text="${user.description}"></td>
            </tr>
        </tbody>
    </table>
</body>
<!-- 引入靜態資源 -->
<script th:src="@{/js/jquery-1.9.1.min.js}" type="application/javascript"></script>
</html>

 

  本地打開

 

  服務容器打開,登陸失敗頁面效果

   

  服務容器打開,登陸成功頁面效果

 

  標準表達式

  簡單表達
  變量表達式: ${...}
  選擇變量表達式: *{...}
  消息表達式: #{...}
  連接網址表達式: @{...}
  片斷表達式: ~{...}

  字面
  文本文字:'one text','Another one!',...
  號碼文字:0,34,3.0,12.3,...
  布爾文字:true,false
  空字面: null
  文字標記:one,sometext,main,...
  文字操做:
  字符串鏈接: +
  文字替換: |The name is ${name}|

  算術運算
  二元運算符:+,-,*,/,%
  減號(一元運算符): -

  布爾運算
  二元運算符: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'))

  官網表達式介紹:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standard-expression-syntax

  

  後記

  springboot+thymeleaf,先後端分離已經成爲了趨勢,這裏進行學習記錄整理,以避免之後又要處處查資料。

 

  補充

  2019-07-24補充:除此以外,thymeleaf還內置了不少對象,能夠從上下文獲取數據,還有好多對象的操做方法,具體請看:

  附錄A:表達式基本對象:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects

  附錄B:表達式實用程序對象:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects

  

  好比:

  在頁面獲取項目路徑

    //項目路徑
    var ctx = [[${#request.getContextPath()}]];

   判斷集合長度

<p th:if="${#lists.size(list)} < 25">
    <p>list集合長度小於25!</p>
</p>

  字符串全大寫、小寫

<p th:text="${#strings.toUpperCase(name)}"></p>

<p th:text="${#strings.toLowerCase(name)}"></p>

  有一點要注意,使用這些內置對象,方法傳參裏面不須要再用${}來取值了,例如,後臺傳過來的名稱叫name

  錯誤使用:

<p th:text="${#strings.toUpperCase($(name))}"></p>

  正確使用:

<p th:text="${#strings.toUpperCase(name)}"></p>

 

  更多內置對象方法請看官網!

 

  補充:本地環境不報錯,Linux環境下報錯,模板不存在:Error resolving template [/bam/login], template might not exist or might not be accessible by any of the configured Template Resolvers

  解決:

  把/去掉就能夠了

 

  

 

 

  代碼開源

  代碼已經開源、託管到個人GitHub、碼雲:

  GitHub:https://github.com/huanzi-qch/springBoot

  碼雲:https://gitee.com/huanzi-qch/springBoot

相關文章
相關標籤/搜索