江帥帥:精通 Spring Boot 系列 04

奈學教育發表於2020-06-16

1. Web 開發的支援

使用 Spring Boot 實現 Web 開發更加便捷了,因為直接依賴 spring-boot-starter-web 模組即可支援 Web 開發,此模組預定義了 Web 開發中常用的依賴包,還有內嵌的 Tomcat 作為預設 Web 容器。

2. Thymeleaf 模板引擎

目前,多數企業級應用開發中都支援前後端分離,但還有少數離不開檢視層技術,Spring Boot 提供了很多模板引擎來支援檢視層技術,比如 Thymeleaf、Freemarker、Velocity。

Thymeleaf 是官方推薦使用的新一代 Java 模板引擎,並支援 HTML 原型,模板表示式在脫離執行環境下不汙染 HTML 結構,能讓前端直接透過瀏覽器檢視基本樣式,也能讓後端使用真實資料檢視展示效果。

3. 整合使用 Thymeleaf 模板

3.1. 建立工程

建立一個 Spring Boot 工程,編輯 pom.xml 檔案,新增 web 和 thymeleaf 依賴。另外,App 啟動類與之前一致。

< 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>

3.2. 新增檢視檔案

在 src/main/resources/templates 目錄下,新建 nicebook.html 檔案。

<!DOCTYPE html>
< html  lang= "en"  xmlns:th= ">
     < head>
         < meta  charset= "UTF-8">
         < title> 良心好書 </ title>
     </ head>
     < body>
         < table  border= "1">
             < tr>
                 < td> 序號 </ td>
                 < td> 好書 </ td>
                 < td> 作者 </ td>
             </ tr>
             < tr  th:each= "book:${books}">
                 < td  th:text= "${book.id}"> </ td>
                 < td  th:text= "${book.name}"> </ td>
                 < td  th:text= "${book.author}"> </ td>
             </ tr>
         </ table>
     </ body>
</ html>

3.3. 配置 Thymeleaf

如果想自定義 Thymeleaf 配置引數,可以在 application.properties 檔案中進行配置,常見的配置選項如下:

# 模板檔案存放位置
spring.thymeleaf.prefix=classpath:/templates/

# 是否開啟快取,預設為 true,開發時可設定為 false
spring.thymeleaf.cache=true

# 檢查模板位置是否存在,預設為 true
spring.thymeleaf.check-template-location=true

# 檢查模板是否存在,預設為 true
spring.thymeleaf.check-template=true

# 模板檔案字尾設定
spring.thymeleaf.suffix=.html

# 模板檔案編碼設定
spring.thymeleaf.encoding=UTF-8

# Content-Type 配置
spring.thymeleaf.servlet.content-type=text/html

3.4. 建立 POJO

public   class  Book  {

     private  Integer id;
     private  String name;
     private  String author;

     // getter 和 setter 方法
}

3.5. 建立 BookController 控制器

@Controller
public   class  BookController  {

     @GetMapping ( "/books" )
     public ModelAndView  books ()  {

        List<Book> bookList =  new  ArrayList<>()

        Book book1 =  new  Book();
        book1.setId( 1 );
        book1.setName( "《碼農翻身:用故事給技術加點料》" );
        book1.setAuthor( "劉欣" );

        Book book2 =  new  Book();
        book2.setId( 2 );
        book2.setName( "《漫畫演算法:小灰的演算法之旅(全綵)》" );
        book2.setAuthor( "魏夢舒" );

        bookList.add(book1);
        bookList.add(book2);

        ModelAndView mv =  new  ModelAndView();
        mv.addObject( "bookList" );
        mv.setViewName( "nicebook" );
         return  mv;
    }
}

3.6. 執行測試

瀏覽器中訪問:,即可看到如下頁面。

attachments-2020-06-UzoF434H5ee8418af3cff.png

4. Thymeleaf 的支援

Spring Boot 透過 org.springframework.boot.autoconfigure.thymeleaf 包為 Thymeleaf  提供了自動配置,涉及到的類如下:

attachments-2020-06-rBoGCr6o5ee84199b2d8e.png

其中 ThymeleafAutoConfiguration 和 ThymeleafProperties 類是比較重要的,前者對整合所需要的 Bean 進行自動配置,後者主要讀取 application.properties 配置檔案,可自定義 Thymeleaf 的屬性和預設配置。

ThymeleafProperties 類部分原始碼如下:

@ConfigurationProperties (
    prefix =  "spring.thymeleaf"
)
public   class  ThymeleafProperties  {
     private   static   final  Charset DEFAULT_ENCODING;
     public   static   final  String DEFAULT_PREFIX =  "classpath:/templates/" ;
     public   static   final  String DEFAULT_SUFFIX =  ".html" ;
     private   boolean  checkTemplate =  true ;
     private   boolean  checkTemplateLocation =  true ;
     private  String prefix =  "classpath:/templates/" ;
     private  String suffix =  ".html" ;
     private  String mode =  "HTML" ;
     private  Charset encoding;
     private   boolean  cache;
     private  Integer templateResolverOrder;
     private  String[] viewNames;
     private  String[] excludedViewNames;
     private   boolean  enableSpringElCompiler;
     private   boolean  renderHiddenMarkersBeforeCheckboxe s;
     private   boolean  enabled;
     private   final  ThymeleafProperties.Servlet servlet;
     private   final  ThymeleafProperties.Reactive reactive;

    ...   
}

5. 擴充:Thymeleaf 常用語法

5.1. 使用 URL

透過 @{…} 來處理常見 URL。

< a  th:href= "@{}"> 奈學教育 </ a>

< a  th:href= "@{/}"> 奈學教育 </ a>

< a  th:href= "@{books/java/one.png}"> 奈學教育 </ a>

5.2. 使用表示式

主要用來從模板中的 WebContext 獲取param、request、session 和 application 中的屬性。使用 ${x} 即可返回儲存在 Thymeleaf 上下文中的變數 x 或作為 request 作用域中的屬性。

${param.x}  能夠返回名為 x 的請求引數;
${session.x}  能夠返回名為 x 的 HttpSession 作用域中的屬性;
${application.x}  能夠返回名為 x 的 ServletContext 作用域中的屬性。

5.3. 使用字串

如果需要對一段文字中的某一處進行替換,可以使用 |…| 這種便捷方式,但不能包含其他常量、條件表示式,只能包含變數表示式 x即可返回儲存在Thymeleaf上下文中的變數x或作為request作用域中的屬性。¨G7G¨K25K如果需要對一段文字中的某一處進行替換,可以使用∣…∣這種便捷方式,但不能包含其他常量、條件表示式,只能包含變數表示式{…},有一定侷限性。

< span  th:text= "|hello, ${userName}|"> </ span>

5.4. 使用運算子

平時看到的算術運算子和邏輯運算子都可以使用。

5.5. 使用條件判斷

可以使用 th:if 和 th:unless 屬性進行條件判斷,前者條件成立時顯示,後者不成立時才顯示。也可以使用 Switch 結構,預設選項使用 * 來表示。

< a  th:href= "index.html"  th:if= ${name !=  null}> 奈學教育 </ a>

< div  th:switch= "${books}">
     < p  th:case= "'Java'"> Java 從入門到逃難 </ p>
     < p  th:case= "'Python'"> Python 從入門到逃難 </ p>
</ div>

5.6. 使用迴圈

使用 th:each 即可實現迴圈。

< tr  th:each= "book : ${bookList}">
     < td  th:text= "${book.id}"> </ td>
     < td  th:text= "${book.name}"> </ td>
     < td  th:text= "${book.author}"> </ td>
</ tr>

5.7. 使用內建物件

透過 # 可以直接訪問 Thymeleaf 的內建物件。

#dates:日期
#calendars:日曆
#numbers:數值格式化
#strings:字串格式化
#objects:物件
#maps:Map 操作工具
#aggregates:運算元組或集合的工具
#bools:布林
#sets:Set 操作工具
#messages:訊息
#arrays:Array 操作工具
#lists:List 操作工具

來源於:奈學開發者社群江帥帥

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69976011/viewspace-2698746/,如需轉載,請註明出處,否則將追究法律責任。

相關文章