Thymeleaf筆記

Thymeleaf筆記

內容來自易百教程https://www.yiibai.com/thymeleaf/css

Theymeleaf官方文檔:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#introducing-thymeleafhtml

1、簡介

Thymeleaf 是用於Web和獨立環境的現代服務器端Java模板引擎。前端

Thymeleaf的主要目標是將天然模板帶到您的開發工做流程中,HTM可以在瀏覽器中正確的顯示,而且能夠做爲靜態原型,從而在開發團隊中實現更強大的協做。java

Thymeleaf的主要目標是提供一個優雅和高度可維護的建立模板的方式。 爲了實現這一點,它創建在天然模板的概念之上,以不影響模板做爲設計原型的方式將其邏輯注入到模板文件中。 這改善了設計溝通,彌合了前端設計和開發人員之間的理解誤差。web

1.Thymeleaf能夠處理何種模板

  • HTML
  • XML
  • TEXT
  • JAVASCRIPT
  • CSS
  • RAW

2.標準方言

一個將某些邏輯應用於標記工件(標籤,一些文本,註釋或者僅僅是模板不是標記的佔位符)的對象被稱爲處理器,而這些處理器的集合(可能還有一些額外的工件)是方言組成。核心庫提供的方言是標準方言。spring

3.HelloWorld

使用Servlet進行Helloworld的演示apache

pom.xmlapi

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai</groupId>
    <artifactId>helloworld</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- Provided dependencies -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency> 
        <!-- Compile dependencies -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.7.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
        </plugins>
        <defaultGoal>compile</defaultGoal>
    </build>

</project>

TemplateEngineUtil.java瀏覽器

package com.yiibai.thymeleaf3.config;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import org.thymeleaf.TemplateEngine;

/**
 * Store and retrieves Thymeleaf TemplateEngine into the application servlet context.
 */
@WebListener
public class TemplateEngineUtil {

    private static final String TEMPLATE_ENGINE_ATTR = "com.yiibai.thymeleaf3.TemplateEngineInstance";

    public static void storeTemplateEngine(ServletContext context, TemplateEngine engine) {
        context.setAttribute(TEMPLATE_ENGINE_ATTR, engine);
    }

    public static TemplateEngine getTemplateEngine(ServletContext context) {
        return (TemplateEngine) context.getAttribute(TEMPLATE_ENGINE_ATTR);
    }

}

ThymeleafConfig.javatomcat

package com.yiibai.thymeleaf3.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

/**
 * Thymeleaf configuration.
 */
@WebListener
public class ThymeleafConfig implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        TemplateEngine engine = templateEngine(sce.getServletContext());
        TemplateEngineUtil.storeTemplateEngine(sce.getServletContext(), engine);
    }

    public void contextDestroyed(ServletContextEvent sce) {
    }

    private TemplateEngine templateEngine(ServletContext servletContext) {
        TemplateEngine engine = new TemplateEngine();

        engine.setTemplateResolver(templateResolver(servletContext));
        return engine;
    }

    private ITemplateResolver templateResolver(ServletContext servletContext) {
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(servletContext);
        resolver.setPrefix("/WEB-INF/templates/");
        resolver.setCharacterEncoding("UTF-8");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }

}

indexServlet.java

package com.yiibai.thymeleaf3.web;

import com.yiibai.thymeleaf3.config.TemplateEngineUtil;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;


@WebServlet("/")
public class IndexServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        TemplateEngine engine = TemplateEngineUtil.getTemplateEngine(request.getServletContext());
        WebContext context = new WebContext(request, response, request.getServletContext());        
        response.setCharacterEncoding("utf-8");
        context.setVariable("recipient", "Yiibai");
        engine.process("index.html", context, response.getWriter());
    }
}

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" />
        <title>Thymeleaf3 + Servlet3 示例</title>
    </head> 
    <body>
        <h1>Thymeleaf 3 + Servlet 3 示例</h1>
        <p>
            Hello <span th:text="${recipient}"></span>!
        </p>
    </body>
</html>

2、標準方言

1.啥是標準方言

Thymeleaf是很是很是可擴展的,它容許自定義的名字來定義一組模板屬性(或者甚至是標籤),用自定語法評估計算表達式和應用邏輯。

它還帶有一些稱爲標準方言(稱爲StandardSpringStandard)的東西,它們定義了一組功能,這些功能應該足以知足大多數狀況。能夠識別這些標準方言在模板中的使用,由於它將包含以th前綴開頭的屬性,如<span th:text="...">

2.標準表達式

大多數Thymeleaf屬性容許將它們的值設置爲包含表達式,因爲它們使用的方言,咱們將其稱爲標準表達式。這些表達式能夠有五種類型:

- ${}:變量表達式
- *{}:選擇表達式
- #{}:消息(i18n)表達式
- @{}:鏈接(URL)表達式
- ~{}:片斷表達式

變量表達式${}

變量表示是OGNL表達式

${session.user.name}
<span th:text="${session.user.name}">
<li th:each="book:${books}">

選擇表達式*{}

選擇表達式就像變量表達式同樣,它們不是整個上下文變量映射上執行,而是在先前選擇的對象。

它們說做用的對象由th:object屬性指定:

<div th:object="${book}">
    <span th:text="*{title}">
    </span>
</div>

消息(i18n)表達式#{}

消息表達式(用於國際化、文本外部化)容許從外部源文件中檢索特定於語言環境的消息。經過鍵來引用這引用消息。

<table>
  <th th:text="#{header.address.city}">...</th>
  <th th:text="#{header.address.country}">...</th>
</table>

連接(URL)表達式@{}

連接表達式在構建URL並向其添加有用的上下文和會話信息,對於部署在web服務器的/myapp上下文中的Web引用程序。可使用如下的表達式:

<a href="@{/order/list}"></a>

至關於

<a href="@{/myapp/order/list}"></a>

其中網址也能夠帶參數

<a th:href="@{/order/details(id=${orderId},type=${orderType})}">...</a>

片斷表達式~{}

片斷表達式是一種簡單的方法用來表示標記的片斷並將其移動到模板中,因爲這些片斷能夠被複制,傳遞到其餘模板的參數

經常使用的是th:insert或者th:replace

<div th:insert="~{commons :: main}">...</div>
<div th:with="frag=~{footer :: #main/text()}">
  <p th:insert="${frag}">
</div>

標準表達式中的內容

  • 文字
    • 文本文字,例如:'one text', 'Another one!',
    • 數字文字,例如:0,10, 314, 31.01, 112.83,
    • 布爾文字,例如:true,false
    • Null文字,例如: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)

3、標準url語法

1.絕對網址

用於建立到其餘服務器的連接。它們須要指定一個協議名稱(http://或者https://)

<a th:href="@{https://www.baidu.com}"></a>

會被渲染成

<a th:href="https://www.baidu.com"></a>

2.上下文相關的URL

若是將一個名稱爲myapp.war的文件部署到一個Tomcat服務器中,那麼應用程序通常是經過URL:http://localhost:8080/myapp來訪問,myapp就是上下文名稱。

與上下文相關的URL以/字符開頭

<a href="@{/order/list}"

至關於

<a href="/myapp/order/list">

3.與服務器相關的URL

服務器相關的URL與上下文相關的URL很是類似,只是它們不假定URL要連接到應用程序上下文中的資源,所以容許連接到同一服務器中的不一樣上下文:

<a th:href="@{~/billing-app/showDetails.html}">

當前應用程序的上下文將被忽略,所以儘管應用程序部署在http:// localhost:8080 / myapp,但該URL將輸出:

<a href="/billing-app/showDetails.html">

4.與協議相關的URL

其實是絕對的URL,它將保持用於顯示當前頁面的協議(HTTP,HTTPS)。 它們一般用於包括樣式,腳本等外部資源:

<script th:src="@{//scriptserver.example.net/myscript.js}">...</script>

它將呈現與上面一致的URL(URL重寫除外),如:

<script src="//scriptserver.example.net/myscript.js">...</script>

### 5.添加參數

<a th:href="@{/order/details(id=3,action='show_all')}"></a>

至關於

<a href="/order/details?id=3&action=show_all"></a>

還可使用正常參數的路徑變量的形式包含參數,但在URL的路徑中指定一個佔位符:

<a th:href="@{/order/{id}/details(id=3,action='show_all')}">

上面輸出結果爲:

<a href="/order/3/details?action=show_all">

4、Thymeleaf+SpringMVC實例

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai</groupId>
    <artifactId>springmvc5thymeleaf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Spring MVC - Thymeleaf Integration example</name>

    <properties>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <!-- Embedded Apache Tomcat required for testing war -->

            <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.4.8.v20171121</version>
         </plugin>
        </plugins>
    </build>
</project>

myWebConfig.java

package com.yiibai.spring.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.yiibai.spring.controller")
public class MvcWebConfig implements WebMvcConfigurer {

   @Autowired
   private ApplicationContext applicationContext;

   /*
    * STEP 1 - Create SpringResourceTemplateResolver
    * */
   @Bean
   public SpringResourceTemplateResolver templateResolver() {
      SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();   
      templateResolver.setCharacterEncoding("UTF-8");
      templateResolver.setApplicationContext(applicationContext);
      templateResolver.setPrefix("/WEB-INF/views/");
      templateResolver.setSuffix(".html");
      return templateResolver;
   }

   /*
    * STEP 2 - Create SpringTemplateEngine
    * */
   @Bean
   public SpringTemplateEngine templateEngine() {
      SpringTemplateEngine templateEngine = new SpringTemplateEngine();      
      templateEngine.setTemplateResolver(templateResolver());
      templateEngine.setEnableSpringELCompiler(true);

      return templateEngine;
   }

   /*
    * STEP 3 - Register ThymeleafViewResolver
    * */
   @Override
   public void configureViewResolvers(ViewResolverRegistry registry) {
      ThymeleafViewResolver resolver = new ThymeleafViewResolver();
      resolver.setTemplateEngine(templateEngine());
      registry.viewResolver(resolver);
   }
}

MvcWebApplicationInitializer.java

package com.yiibai.spring.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

   @Override
   protected Class<?>[] getRootConfigClasses() {
      return null;
   }

   @Override
   protected Class<?>[] getServletConfigClasses() {
      return new Class[] { MvcWebConfig.class };
   }

   @Override
   protected String[] getServletMappings() {
      return new String[] { "/" };
   }

}

MyController.java

package com.yiibai.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {

   @GetMapping("/")
   public String index(Model model) {
      model.addAttribute("message", "Hello Spring MVC 5!");
      return "index";
   }
}

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>SpringMVC5+Thymeleaf示例</title>
</head>
<body>
    <h1>Spring MVC + Thymeleaf Hello World example</h1>
    <p th:text="${message}"></p>
</body>
</html>

5、Thymeleaf 顯示bean的值

Product.java

package com.yiibai.spring.bean;

import java.util.Date;

public class Product {

    private String description;
    private Integer price;
    private Date availableFrom;

    public Product(final String description, final Integer price, final Date availableFrom) {
        this.description = description;
        this.price = price;
        this.availableFrom = availableFrom;
    }
    //**** getter and setter**/
}

myController.java

package com.yiibai.spring.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.yiibai.spring.bean.Product;

@Controller
public class MyController {

   @GetMapping("/")
   public String index(Model model) throws ParseException {
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      Product product = new Product("花生油", 129, sdf.parse("2018-02-18"));
      model.addAttribute("product", product);
      return "index";
   }
}

index.html

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
 <link rel="stylesheet" th:href="@{/css/main.css}" />
<title>SpringMVC5+Thymeleaf示例</title>
</head>
<body>
    <h2>Spring MVC5 + Thymeleaf Bean示例</h2>

    <h2>產品信息</h2>
    <dl>
        <dt>產品名稱:</dt>
        <dd th:text="${product.description}">默認產品名稱</dd>

        <dt>產品價格:</dt>
        <dd th:text="${product.price}">350</dd>

        <dt>產品有效時間:</dt>
        <dd th:text="${product.availableFrom}">28-Jun-2018</dd>
    </dl>
</body>
</html>

6、Thmeleaf 迭代

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" th:href="@{/css/main.css}" />
<title>Thymeleaf迭代器示例</title>
</head>
<body>
    <h2>Thymeleaf迭代器示例</h2>
    <table>
        <thead>
            <tr>
                <th>產品名稱</th>
                <th>價格</th>
                <th>有效日期</th>
            </tr>
        </thead>
        <tbody th:remove="all-but-first">
            <tr th:each="product : ${productList}">
                <td th:text="${product.description}">Red chair</td>
                <td th:text="${'¥' + #numbers.formatDecimal(product.price, 1, 2)}">¥350</td>
                <td th:text="${#dates.format(product.availableFrom, 'dd-MM-yyyy')}">2018-02-20</td>
            </tr>
        </tbody>
    </table>

</body>
</html>

7、條件判斷

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" th:href="@{/css/main.css}" />
<style>
span.offer {
    font-weight: bold;
    color: green;
}
</style>
<title>Thymeleaf條件示例</title>
</head>
<body>
    <h2>Thymeleaf條件示例</h2>
    <table>
        <thead>
            <tr>
                <th>行序號</th>
                <th>產品名稱</th>
                <th>價格</th>
                <th>有效日期</th>
                <th>備註</th>
            </tr>
        </thead>
        <tbody th:remove="all-but-first">
            <tr th:each="product : ${productList}">
            <td th:text="${productStat.count}">1</td>
                <td th:text="${product.description}">Red chair</td>
                <td th:text="${'¥' + #numbers.formatDecimal(product.price, 1, 2)}">¥350</td>
                <td th:text="${#dates.format(product.availableFrom, 'dd-MM-yyyy')}">2018-02-20</td>
                <td><span th:if="${product.price gt 100}" class="offer">特殊提供</span></td>
            </tr>
            <
        </tbody>
    </table>

</body>
</html>

8、表單

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" th:href="@{/css/main.css}" />
<title>Thymeleaf 表單示例</title>
</head>
<body>
    <h2>Thymeleaf 表單示例</h2>
    <form th:action="@{/saveProduct}" th:object="${product}" method="POST">
          <label for="firstName">產品名稱:</label>
          <input type="text" th:field="*{name}" value="" /><br/>

          <label for="firstName">有效日期:</label>
          <input type="text" th:field="*{availableFrom}" value="2018-03-28" /> <br/>        

          <label for="price">價格 (RMB):</label>
          <input type="text" th:field="*{price}" size="10" value="198" /><br/>

          <input type="submit" value="提交"/>
    </form>
</body>
</html>
相關文章
相關標籤/搜索