SpringBoot2.0學習第三篇之整合thymeleaf模板引擎

在Java開發(fā)中如果說要問最近幾年最流行的Web開發(fā)框架是什么?可能只會有一個答案。那就是SpringBoot,造成這樣的最大原因是,SpringBoot極大的簡化了Web的開發(fā)流程,可以說是零配置搭建開發(fā)環(huán)境。甚至web.xml的配置也沒有了。使任何新手都可以在5分鐘之內搭建一個Web項目,下面跟著小編來看看,如何在5分鐘內搭建開放環(huán)境。

通讀全文需要3分鐘。

image

教程目錄

image

SpringBoot2.0學習第三篇之整合thymeleaf模板引擎.md

目標是什么?

  1. 快速整合thymeleaf模板引擎
  2. thymeleaf模板基礎語法

開發(fā)環(huán)境

  1. JDK1.8或更高版本
  2. Maven
  3. IntelliJ IDEA 開發(fā)工具

項目目錄

|____resources
| |____templates
| | |____index.html
| | |____book.html
|____java
| |____hello
| | |____WebApplication.java
| | |____controller
| | | |____HelloController.java
| | | |____SyntaxDemoController.java
| | |____entities
| | | |____Book.java

一. 快速整合thymeleaf視圖模板引擎

  System.out.println(String.format("hello:%d", 1));
  System.out.println(String.format("hello:%s", "SpringBoot"));

首先我們先認識一下什么是視圖模板引擎,其實簡單的來看,以上代碼就是一個模板引擎。何為模板引擎其實就是可以將不同數(shù)據(jù)類型,通過處理后,給添加到文本上。像下面這種%s就是String類型的占位符,%d是整型的占位符,而高級的一點的模板引擎是支持更多的語法,比如支持for循環(huán),while循環(huán),條件判斷。就比如thymeleaf,或者是freemaker,或者是jsp之類的模板引擎都是支持的,那么為啥要在前面加一個視圖模板引擎呢,是因為渲染的文本最終會被轉換成html的格式,輸出給客戶端,客戶端如果是瀏覽器訪問,就會把文本直接渲染成可視化的方式展示給用戶。

  • 本文我們給大家演示的模板引擎是thymeleaf,他默認的模板文件是以.html的方式。

  • 而上面所說的freemaker引擎,默認的模板文件是.ftl

在SpringBoot的配置文件中,如果不配置,默認就是下面這樣寫,當然我們也可以自定義模板文件的后綴,和模板文件所在的路徑

  1. 默認模板文件后綴
spring.freemarker.suffix=.ftl
spring.thymeleaf.suffix=.html
  1. 默認模板文件路徑

resources/templates

  1. 靜態(tài)文件路徑(不需要渲染的頁面或者是css,js之類的放這個目錄)

resources/static

好了,在知道以上這些知識儲備后,我們就開始快速的整合thymeleaf吧!

首先添加依賴

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
</dependencies>

添加視圖模板文件

在resources/templates創(chuàng)建,index.html。 注意因為我們整合的是thymeleaf所以我們的后綴要是.html。

如果要是整合freemarker那么我們文件名就要命名為index.ftl

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>軟件編程指南: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<a ><img src="https://ws1.sinaimg.cn/large/006tKfTcgy1g0na8ceb0aj30uj0buwl1.jpg"></a>
<p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>

注意語法:

<p th:text="'Hello, ' + ${name} + '!'" />

添加控制器

可以看到在本節(jié)課程中,我們使用的是@Controller注解,而不是@RestController,那是因為本節(jié)我們是要需要視圖模板引擎處理后才能將數(shù)據(jù)響應給客戶端,而@RestController適合使用在不需要模板引擎處理,直接把數(shù)據(jù)響應給客戶端的場景下。這里入?yún)ame是請求參數(shù),ModelModelAndView是自動注入進來的。

@Controller
public class HelloController {

  @GetMapping("/hello")
  public String greeting(@RequestParam(name = "name", required = false, defaultValue = "World") String name, Model model) {
    model.addAttribute("name", name);
    return "index";
  }
   @GetMapping("/hello2")
  public ModelAndView hello2(@RequestParam(name = "name", required = false, defaultValue = "World") String name, ModelAndView mv) {
    mv.setViewName("index");
    mv.addObject("name", name);
    return mv;
  }
}

當然也可以不自動注入,我們自己創(chuàng)建。像下面這種。

 @GetMapping("/hello3")
  public ModelAndView hello3(@RequestParam(name = "name", required = false, defaultValue =   "World") String name) {
    ModelAndView mv = new ModelAndView("index");
    mv.addObject("name", name);
    return mv;
  }
  • Model 就是視圖層渲染所需要的數(shù)據(jù)
  • ModelAndView 就是視圖層渲染所需要的數(shù)據(jù)和要渲染的視圖

運行啟動

@SpringBootApplication
public class WebApplication {

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

啟動類還是一個Main函數(shù)

main()方法使用Spring Boot的SpringApplication.run()方法啟動應用程序。您是否注意到沒有一行XML?也沒有web.xml文件。此Web應用程序是100%純Java,您無需處理配置任何管道或基礎結構。

恭喜!您剛剛使用Spring Boot開發(fā)了一個網頁。


thymeleaf模板基礎語法

前面說了這些高級的模板引擎是可以處理各種類型的數(shù)據(jù),也支持想for語句或if語句的語法,下面我們來看看如何使用。先看下控制類

@Controller
public class SyntaxDemoController {
  @GetMapping("/book")
  public String index(Model model) {
    Book book = new Book("頸椎病康復指南", "項目經理", new Date(), 23.95,"CG");
    model.addAttribute("book", book);
    model.addAttribute("title", "語法演示");
    model.addAttribute("books", loadBooks());
    model.addAttribute("myMap",loadMap());
    return "book";
  }
  public Map<String,String> loadMap(){
    Map<String,String>map=new ConcurrentHashMap<>();
    map.put("醫(yī)生","C");
    map.put("教授","B");
    map.put("演員","C");
    return map;
  }
  public List<Book> loadBooks() {
    List<Book> books = new ArrayList<>();
    books.add(new Book("Java開發(fā)指南", "Jay", new Date(), 99.2,"PT"));
    books.add(new Book("Python從入門到放棄", "Lin", new Date(), 43.8,"CX"));
    books.add(new Book("NodeJs實戰(zhàn)", "XD ", new Date(), 234.23,"*"));
    return books;
  }
}

  1. 變量賦值

<title th:text="${title}"></title>

  1. 對象賦值
 <tr>
        <td th:text="${book.getName()}">默認值</td>
        <td th:text="${book.getAuthor()}">默認值</td>
        <td th:text="${#dates.format(book.getDate(), 'yyyy-MM-dd hh:mm:ss')}">默認值</td>
        <td th:text="${book.getPrice()}">默認值</td>
 </tr>

在數(shù)據(jù)模型Model 中添加一個變量book,就可以直接在目標中使用(Book必須有getset方法)

  1. switch語法
<!--switch判斷-->
<td th:switch="${book.getSaleType()}">
  <span th:case="'CG'">閃購</span>
  <span th:case="'PT'">拼團</span>
  <span th:case="'CX'">促銷</span>
  <span th:case="*">其它</span>
</td>
  1. 集合賦值
<!--讀物實體列表-->
    <tr th:each="product : ${books}">
        <td th:text="${product.getName()}">默認值</td>
        <td th:text="${product.getAuthor()}">默認值</td>
        <td th:text="${#dates.format(product.getDate(), 'dd-MM-yyyy')}">默認值</td>
        <td th:text="${'¥' + #numbers.formatDecimal(product.getPrice(), 1, 2)}">默認值</td>
        <!--switch語法-->
        <td th:switch="${product.getSaleType()}">
            <span th:case="'CG'">閃購</span>
            <span th:case="'PT'">拼團</span>
            <span th:class="${product.getPrice() gt 40}?'offer'" th:case="'CX'">促銷</span>
            <span th:case="*">其它</span>
        </td>
    </tr>
  1. if判斷
<!--if語句語法-->
<span th:if="${book.getPrice() gt 60}" class="offer">if語句語法</span>
  1. map集合
 <!--map-->
 <div th:each="key,v:${myMap}">
   <p th:text="${'索引:'+v.index+'Key:'+key.getKey()+'value:'+key.getValue()}"></p>
 </div>

獲取本課程代碼

  • 獲取方式,私信: 003
    小編編輯很辛苦,希望得到您的點擊關注,和小編一起學習SpringBoot。

更多了解可以點擊小編博客: https://blog.springlearn.cn/posts/4135/

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容