微服務 SpringBoot 2.0(五):整合Thymeleaf模板引擎

我只認識Freemarker、Velocity、JSP,Thymeleaf是啥子 —— Java面試必修css

引言

在web開發服務中,重要的莫過於前端界面,一個好的模板引擎能讓前端的數據綁定更便捷。對於SEO而言,好的模板引擎也有着足夠的優點,因此今天咱們要講解的是Thymeleaf模板引擎html

在接下來的文章中,我在末尾處會公佈源碼,源碼將託管在碼雲上前端

初識

工具

SpringBoot版本:2.0.4
開發工具:IDEA 2018
Maven:3.3 9
JDK:1.8jquery

你可能用過Freemarker,用過Velocity,但連Thymeleaf都沒有據說過,不要慌,咱們一塊兒來瞧瞧。git

Thymeleaf是一款用於渲染XML、XHTML、HTML5內容的模板引擎。與Velocity,FreeMaker,JSP相似,它也能夠輕易的與Spring MVC等Web框架進行集成做爲Web應用的模板引擎,與其它模板引擎相比,Thymeleaf最大的特色是可以直接在瀏覽器中打開並正確顯示模板頁面,而不須要啓動整個Web應用,是否是猴塞雷啊。web

官網:http://www.thymeleaf.org/面試

SpringBoot支持的模板引擎

  • FreeMarker
  • Groovy
  • Thymeleaf(官方推薦)
  • Mustache

JSP技術Spring Boot官方是不推薦的,緣由以下:spring

  • tomcat只支持war的打包方式,不支持可執行的jar。
  • Jetty 嵌套的容器不支持jsp
  • Undertow
  • 建立自定義error.jsp頁面不會覆蓋錯誤處理的默認視圖,而應該使用自定義錯誤頁面

Thymeleaf是Spring Boot首要支持的模板引擎,當你使用上述模板引擎中的任何一個,它們默認的模板配置路徑爲:src/main/resources/templates。固然也能夠修改這個路徑,具體如何修改,可在後續各模板引擎的配置屬性中查詢並修改。瀏覽器

Thymeleaf優勢

  • Spring MVC中@Controller中的方法能夠直接返回模板名稱,接下來Thymeleaf模板引擎會自動進行渲染
  • 模板中的表達式支持Spring表達式語言(Spring EL)
  • 表單支持,併兼容Spring MVC的數據綁定與驗證機制
  • 國際化支持

來觀察一段代碼緩存

<table>
  <thead>
    <tr>
      <th th:text="#{msgs.headers.name}">Name</th>
      <th th:text="#{msgs.headers.price}">Price</th>
    </tr>
  </thead>
  <tbody>
    <tr th:each="prod: ${allProducts}">
      <td th:text="${prod.name}">Oranges</td>
      <td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td>
    </tr>
  </tbody>
</table>

 

是否是看起來仍是很簡單啊,對於開發人員來講,弄懂裏面常常使用的幾個標籤應該就夠了

動起來

構建一個簡單的頁面

1、引入依賴
<!--thymeleaf模板引擎,無需再引入web模塊-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 

 
maven依賴更新

引入該依賴後會自動引入web依賴,不須要再單獨引入web依賴。

2、編寫Controller
@Controller
@SpringBootApplication
public class ThymeleafDemo1Application {

    @RequestMapping("/thymeleaf1")
    public ModelAndView thymeleaf1(){

        List<DemoBean> demoBeans = new ArrayList<DemoBean>();
        DemoBean demoBean = new DemoBean();
        demoBean.setName("Java面試必修");
        demoBean.setUrl("www.itmsbx.com");
        demoBeans.add(demoBean);

        demoBean = new DemoBean();
        demoBean.setName("對象無憂");
        demoBean.setUrl("www.51object.com");
        demoBeans.add(demoBean);

        demoBean = new DemoBean();
        demoBean.setName("上海恆驪信息科技");
        demoBean.setUrl("www.henliy.com");
        demoBeans.add(demoBean);

        ModelAndView mav = new ModelAndView("/thymeleaf1");
        mav.addObject("demoBeans",demoBeans);
        mav.addObject("hint","想學習更多面試技巧和知識,請關注公衆號:Java面試必修(itmsbx)");
        return mav;
    }

    public static void main(String[] args) {
        SpringApplication.run(ThymeleafDemo1Application.class, args);

    }
}

 

2、編寫html

因爲src/main/resources/templates目錄是SpringBoot默認指定的映射目錄,因此咱們再resources下新建templates目錄,而後再新建一個thymeleaf1.html頁面

頁面內容以下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>learn Resources</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<div style="text-align: center;margin:0 auto;width: 1000px; ">
    <h2 th:text="${hint}"></h2>
    <table width="100%" border="1" cellspacing="1" cellpadding="0">
        <tr>
            <td>名稱</td>
            <td>網址</td>
        </tr>
        <!--/*@thymesVar id="demoBeans" type=""*/-->
        <tr th:each="demo : ${demoBeans}">
            <td th:text="${demo.name}">對象無憂</td>
            <td><a th:href="${demo.url}" target="_blank">點我</a></td>
        </tr>
    </table>
</div>
</body>
</html>

 

注:上述代碼,經過xmlns:th=」[http://www.thymeleaf.org](http://www.thymeleaf.org/)「命令空間,將靜態頁面轉換爲動態的視圖,須要進行動態處理的元素將使用「th:」前綴。

3、運行查看

執行run方法,打開瀏覽器訪問 http://localhost:8080/thymeleaf1,即可看到以下結果

 
運行結果
小結

1、新建帶有SpringBoot註解的控制器類
2、在resources目錄下建立templates目錄
3、 在templates目錄下建立.html模板文件
4、使用模板:
1. 模板文件頭部使用 <html xmlns:th="http://www.thymeleaf.org">定義
2. html標籤上使用 th:開頭標識做爲前綴
3. 訪問數據使用${}
4.經過 @{}引入web靜態文件<link rel="stylesheet" th:href="@{/css/jquery.min.css}"/>(暫未使用)

Thymeleaf的默認參數配置

在properties或yml中能夠配置thymeleaf模板解析器屬性,下面是部分yml格式的屬性

  # THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf:
  #開啓模板緩存(默認值:true)
  cache: true

  #Check that the template exists before rendering it.
  check-template: true

  #檢查模板位置是否正確(默認值:true)
  check-template-location: true

  #開啓MVC Thymeleaf視圖解析(默認值:true)
  enabled: true

  #模板編碼
  encoding: UTF-8

  #要被排除在解析以外的視圖名稱列表,用逗號分隔
  spring.thymeleaf.excluded-view-names: 

  #要運用於模板之上的模板模式。另見StandardTemplate-ModeHandlers(默認值:HTML5)
  mode: HTML5

  #在構建URL時添加到視圖名稱前的前綴(默認值:classpath:/templates/)
  prefix: classpath:/templates/

  #在構建URL時添加到視圖名稱後的後綴(默認值:.html)
  suffix: .html

  #Thymeleaf模板解析器在解析器鏈中的順序。默認狀況下,它排第一位。順序從1開始,
  #只有在定義了額外的TemplateResolver Bean時才須要設置這個屬性。
  template-resolver-order:

  #可解析的視圖名稱列表,用逗號分隔
  spring.thymeleaf.view-names:

 

總結

關於Thymeleaf模板引擎整合就到這裏結束了,你們是否是以爲很簡單呢,趕忙動手起來吧。關於更多模板的屬性配置我將在Spring Boot 經常使用配置(properties、yml)這章給你們列出來

源碼地址:

https://gitee.com/rjj1/SpringBootNote/tree/master/demo


做者有話說:喜歡的話就請移步Java面試必修網 www.itmsbx.com,請自備水,更多幹、幹、乾貨等着你

相關文章
相關標籤/搜索